Blue Theme Orange Theme Green Theme Red Theme
 
Mindcracker MVP Summit 2012
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » String & StringBuilder » Generating Random Number and String in C#

Generating Random Number and String in C#

The Random class defined in the .NET Framework class library provides functionality to generate random numbers. This article shows you how you can use this class to generate random numbers and strings and even combination of both.

Author Rank :
Page Views : 1251543
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Mindcracker MVP Summit 2012
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

The Random class defined in the .NET Framework class library provides functionality to generate random numbers.

The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value.

The Random class has three public methods - Next, NextBytes, and NextDouble. The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0. The Next method has three overloaded forms and allows you to set the minimum and maximum range of the random number.

The following code returns a random number:

int num = random.Next();

The following code returns a random number less than 1000.

int num = random.Next(1000);

The following code returns a random number between min and max:

private int RandomNumber(int min, int max)
{
Random random =
new Random();
return random.Next(min, max);
}

At some point, you may also want to generate random strings. I have created a method, which takes first parameter as the size of string and second parameter if you want the string to be lowercase.

/// <summary>
/// Generates a random string with the given length
/// </summary>
/// <param name="size">Size of the string</param>
/// <param name="lowerCase">If true, generate lowercase string</param>
/// <returns>Random string</returns>
private string RandomString(int size, bool lowerCase)
{
StringBuilder builder =
new StringBuilder();
Random random =
new Random();
char ch ;
for(int i=0; i<size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
builder.Append(ch);
}
if(lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}

You can even combine the two methods - RandomNumber and RandomString to generate a combination of random string and numbers. For example, the following code generates a password of length 10 with first 4 letters lowercase, next 4 letters numbers, and last 2 letters as uppercase.

public string GetPassword()
{
StringBuilder builder =
new StringBuilder();
builder.Append(RandomString(4,
true));
builder.Append(RandomNumber(1000, 9999));
builder.Append(RandomString(2,
false));
return builder.ToString();
}

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Mindcracker MVP Summit 2012
Become a Sponsor
 Comments
Good by rabail On March 10, 2007
thnxx mr mahesh,,it helped me alot. As being a student,i was stucked with random numbers generation bla bla ... thnx.
Reply | Email | Modify 
Re: Good by Mahesh On March 13, 2007
No problem.
Reply | Email | Modify 
Good example by Rajesh On April 11, 2007
Hi mahesh, Thanx for this example, i wanted to know how to generate random number in C# (for my final year project) and with my keyword your link was the first one in google, it was great. i still haven't tried the example, but i know it will work, coz programming is a part of me inside :) take care... - Rajesh (www.rajesh.sentosajaipur.com)
Reply | Email | Modify 
c# by Nitin On April 13, 2007
how to generate serial no.using random function
Reply | Email | Modify 
Interesting by Michael On June 19, 2007
I found that placing "Random random = new Random();" outside the function returned random strings when calling "RandomString()" repeatedly. Developers commonly place this inside the function but it is better to seed outside the function. ~M
Reply | Email | Modify 
Re: Interesting by Mahesh On June 21, 2007
Good finding. Thanks M.
Reply | Email | Modify 
Good, but... by Gay On July 26, 2007
Here's a simpler function that uses an external Random() object & allows you to specify legal characters.

private static string RandomString(int size, Random r)
{
     string legalChars = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXZY";
     stringBuilder sb = new StringBuilder();
     for (int i = 0; i < size; i++)
         sb.Append(legalChars.Substring(r.Next(0, legalChars.Length - 1), 1));
     return sb.ToString();
}
Reply | Email | Modify 
I dont get it by noor rifhan On July 31, 2007
I want to get a string of numbers upon clicking a button. How can i get that?
Reply | Email | Modify 
Re: I dont get it by Mahesh On August 2, 2007

Here is the updated code. In below method, change size for your range of the number.

private static string RandomString()

{

   int size = 9;

   Random r = new Random();

   string legalChars = "123456789";

   StringBuilder sb = new StringBuilder();

   for (int i = 0; i < size; i++)

     sb.Append(legalChars.Substring(r.Next(0, legalChars.Length - 1), 1));

   return sb.ToString();

}

Copy and paste this method and call RandomString() method from your code.

Reply | Email | Modify 
good by mahindra On September 13, 2007
when i tried with that code, its asking me to add reference libraries.. which libraries ?? where to add and how to add thos libraries in c#.net ?? plz suggest me
Reply | Email | Modify 
good by mahindra On September 13, 2007
when i tried with that code, its asking me to add reference libraries.. which libraries ?? where to add and how to add thos libraries in c#.net ?? plz suggest me
Reply | Email | Modify 
Re: good by Mahesh On September 17, 2007

Make sure you have System.IO namespace defined for StringBuilder class. Random class is defined in System namespace which is included by default.

Reply | Email | Modify 
Re: good by David On October 1, 2007
Add using System.Text; at the beginning of the file where you using the StringBuilder class. Sean
Reply | Email | Modify 
Get First and Last name by Kunal On October 10, 2007
In my application I have to generate Customer name randomly. What should I do to generate First and Last name of a customer that make sense. Random string is not going to help bcz it will create names that does not exist. And Number of Customers starts from 500 up to 1000, so we do not want any repeatation, also.
Reply | Email | Modify 
Re: Get First and Last name by Mahesh On April 7, 2009
Ok this is what you can do.
1. Create an ArrayList = AlreadyGeneratedNumbersList
2. RandNumber = Generate a random number between 500 and 1000.
3. If AlreadyGeneratedNumbersList does not have RandNumber, Add RandNumber to AlreadyGeneratedNumbersList
4. Add that number to a string "First Name" + "Last Name" + RandNumber

This should be your random name with no duplication.

Reply | Email | Modify 
c sharp by bhavani On October 23, 2007
i am having "serial number" column in datagridview after completing the end of the row i press enter key "serial number" column should increment from first row by 1(by value one)
Reply | Email | Modify 
awesome this what i wanted. by Muzikayise On January 26, 2008
thanks mate. I have just recently made the switch from VB.NET to C#. I don't know much about C# but the goal is to become a master at it. any suggestions where I can find articles for beginners?
Reply | Email | Modify 
Re: awesome this what i wanted. by Mahesh On April 7, 2009
Here are some beginner tutorials and free books.
http://www.c-sharpcorner.com/Beginners/
Reply | Email | Modify 
tell me code by Akhilesh On August 29, 2008
i want to generate random number without duplicate number. how its possible
Reply | Email | Modify 
tell me code by Akhilesh On August 29, 2008
i want to generate random number without duplicate number. how its possible
Reply | Email | Modify 
akhi2485 by Akhilesh On August 29, 2008
I want to generate random number without duplicate any of the numbers. How is this possible?
Reply | Email | Modify 
Re: akhi2485 by Mahesh On April 7, 2009
Please see my next comment.
Reply | Email | Modify 
non repeatable random numbers ? by pankaj On November 27, 2008
sir does this code generate non repeating random numbers........ int num = random.Next(); i need non repeating numbers sir............ !
Reply | Email | Modify 
Re: non repeatable random numbers ? by Mahesh On April 7, 2009
I don't think it will consider duplicate numbers. You can deal with this by increasing the number range and store the already generated numbers in memory and if same number is generated, and found in your list, generate next.
Reply | Email | Modify 
Generate random numbers by Anitha On April 29, 2009
here is a simple fns which will return you a randum number private static int GetRandomNo(int MaxValue) { RandomNumberGenerator rng = RNGCryptoServiceProvider.Create(); byte[] bytes = new byte[4]; rng.GetBytes(bytes); int rndNum = BitConverter.ToInt32(bytes, 0); return Math.Abs(rndNum % MaxValue); }//Max Value is max range
Reply | Email | Modify 
please suggest by jeet On May 4, 2009
Dear Sir,
thanks for the article, however my need is bit tricky, can you shed some light on this?

I have a database table with primary key (int) - values are randomly generated values between -2 Billion to +2 Billion (except values between 0-100) -  this table is already filled with some records - now I have a CSV to export into table that has all the records except this primary key column (I need to handle it programmatically) with following conditions in mind

1. value should be random between -20Bl to +20Bl (except 0-100)
2. performance should be good (arond 20K records in CSV)

I would be more than happy if you can reply directly at havejeet@gmail.com

bunch of thanks
Jeet
Reply | Email | Modify 
Simple Random String by Bill On September 21, 2009
Here's a bit more straightforward random String builder:

protected String CreateTemporaryPassword(int intPasswordLength)

{

Random rndmRandom = new Random();

StringBuilder sbPassword = new StringBuilder();

while (sbPassword.Length < intPasswordLength)

{

int intRandomValue = 0;

while (intRandomValue == 0)

{

intRandomValue = rndmRandom.Next(65,90); // UpperCase Letters Only

if (intRandomValue == 73) intRandomValue = 0; // Don't allow "I" because it looks too much like a one (1)

if (intRandomValue == 79) intRandomValue = 0; // Don't allow "O" because it looks too much like a zero (0)

}

sbPassword.Append((Char)intRandomValue);

}

return sbPassword.ToString();

}

Reply | Email | Modify 
Thanks by Nithya On February 1, 2010
Thanks for your detailed information. I have learnt from this
Reply | Email | Modify 
problem inserting data from one gridview to another gridview with some check conditions by zeeshan On February 10, 2010
Dear mahesh,
 I have to datagridviews in C# windows application. grid1 contains some records columns like (item name, Qty). and grid2 is empty initially. what i am doing , reading first record from grid1 & inserting into Grid2. now wat i want, while reading 2nd record from grid1 & comparing(item name) it with existing records in grid2  if same record is found it should  update the qty of existing record in grid2  else new row inserted into grid2. 
how can i do this?
i hope that i make you  understand with my problem. Please tell what should i do?? 
Thanks

Reply | Email | Modify 
Names of Customers using random function by Sonam On April 11, 2010
In my application I have to generate Customer name randomly. What should I do to generate Name of a customer that make sense. And Number of Customers starts from 1 up to 10, so we do not want any repeatation, also.
how do i display the names of the customers in data grid.
Please help...
Thank u
Reply | Email | Modify 
Number generator by Andrew On April 20, 2010
hey i'm a student and i am trying to generate 100 random numbers by a click of a button
i can generate random numbers, but i can't get it to generate 100 numbers at a time. can anyone help?
Reply | Email | Modify 
thanks by Mesha On May 21, 2010

thank you very much

Reply | Email | Modify 
Generate serial number of 14 digits by Mesha On June 5, 2010

sir please,

i'd like to know how to generate serial number of 14 digits that can be stored in database and everytime a number is automatically added when the additional  button is pressed.And that number is similar to serial numbers of telecommunication cards.
thank you for your cooperation
please do'nt late to answer me

Reply | Email | Modify 
Re: Generate serial number of 14 digits by S On June 5, 2010
Hallo,
You can try this:

        private const int MAXNUMBERS = 14;

        private string generateSerialNum()
        {
            Random r = new Random();
            StringBuilder sb = new StringBuilder();
            int size = MAXNUMBERS;
            string legalNums = "0123456789";

            for (int i = 0; i < size; i++)
            {
                sb.Append(legalNums.Substring(r.Next(0, legalNums.Length - 1) + 1, 1));
            }
            return sb.ToString();
        }

        // on click
        private void genSerialnumButton_Click(object sender, EventArgs e)
        {
            serialNumTextBox.Text = generateSerialNum();
        }
Reply | Email | Modify 
Random nos with non repating values by Syed Kamran On June 14, 2010
Is there any way to generate Random nos. with non repeating values.....?
Reply | Email | Modify 
Re: Random nos with non repating values by Mahesh On June 15, 2010
One way you can implement this is, store previously generated random numbers somewhere in memory (if you are generating now) or load from whereever you have stored (if any) and when a new number is generated, check it it is already in the list. If found in the list, generate another random number.
Reply | Email | Modify 
Is C# random number generator is secured? by Jo On June 14, 2010
I am mainly working on C++, to make a random number you have to assign a generator for random seek (like GetTickCount() or GetCurrentTime()) then you can use the rnd function.
I wonder if it is secured as in C++
Thank you
Reply | Email | Modify 
Re: Is C# random number generator is secured? by Mahesh On June 15, 2010
I am really not sure Jo.
Reply | Email | Modify 
created number's lenght by Abdullah On June 18, 2010
I have done an application like this.But I want to generate too long numbers.(for example 0 between 20000000) How can I do? Or can I do?

(I'm sorry if I have mistakes in my comment)
Reply | Email | Modify 
How to do random image by Safaa On June 18, 2010
I wanna know how you can do ranom image from database when the page refreshed, hint I know how you can retrived the image from database so just i know How to do random image??
thanks so much
Reply | Email | Modify 
generate serial number by Mesha On June 21, 2010
Thank you s
But this way the number generated by changes in each time we the implementation process, but I want to generate number looks like 20100000000001 and increasing each time by one looks like 20100000000002 and so continue every time up by one at each execution, and only change in the year again, where it think 2010 is the year and changes each year new and start all over again 20110000000001

thank you for your cooperation
Reply | Email | Modify 
how to call it ? by kopapoooo On August 2, 2010
how to call it ?
Reply | Email | Modify 
The name Random does not exist in the current context by marshall On October 10, 2010

I just want to kw . I tried to run the program on isual studio 2008.

Reply | Email | Modify 
i tried to run your code but it did not go by marshall On October 10, 2010
Mahsh,
Please i tried to run your first code   but it kept on saying " thename Random does not exist in the currn context
Reply | Email | Modify 
i tried to run your code but it did not go by marshall On October 10, 2010
Mahsh,
Please i tried to run your first code   but it kept on saying " thename Random does not exist in the currn context
Reply | Email | Modify 
Re: i tried to run your code but it did not go by Mahesh On November 7, 2010
Random class is defined in the System namespace. Is this a C# application? If yes, what kind of project it is?


Reply | Email | Modify 
I think by Mizan On January 6, 2011
I think it's a fantastic work of you! But as beginner which process should i follow to learn c#. Please, give me instruction!
Reply | Email | Modify 
Re: I think by Mahesh On January 6, 2011
As a beginner, you can start here: http://www.c-sharpcorner.com/Beginners/
Reply | Email | Modify 
Broken RandomNumber method by Brian On January 31, 2011
Your RandomNumber method is implemented poorly. [code] private int RandomNumber(int min, int max) { Random random = new Random(); return random.Next(min, max); }[/code] Doing this will seed the RNG with the same value if it is called quickly enough in the same timeframe, causing duplicate results. However, if you wrote the helper method like this: [code] Random random = new Random(); private int RandomNumber(int min, int max) { return random.Next(min, max); } [/code] it will be seeded just once and work properly!
Reply | Email | Modify 
Request by Jinal On February 22, 2011
Hi its nice to read this but i have one confusion how can i display this string in wave kind of form as we usually see in registration forms and all pls help me if you have any idea for the same. Thanks.
Reply | Email | Modify 
Request by Jinal On February 22, 2011
Hi its nice to read this but i have one confusion how can i display this string in wave kind of form as we usually see in registration forms and all pls help me if you have any idea for the same. Thanks.
Reply | Email | Modify 
Re: Generating Random Number and String in C# by Lars On March 2, 2011
I use a slightly different method to generate random strings... private string _passwordArray = "!#$%&'()*+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"; public static string Generate(int Length) { Random random = new Random(); StringBuilder password = new StringBuilder(); // fill the StringBuilder text with a random password of given length for (int i = 0; i < Length; i++) { // get an integer between 1 and the length of the password character array int index = (int)Math.Ceiling(random.NextDouble() * _passwordArray.Length); // append it to the string password.Append(_passwordArray[index]); } // return the random password return password.ToString(); } In this way, you merely have to adjust the character array to the selection of characters you want
Reply | Email | Modify 
Alternative using Guid by dron On March 27, 2011
private int GetRandom(int len) { string guid = Guid.NewGuid().ToString(); double number = 0; int counter = 0; foreach (char c in guid) { number += Convert.ToInt32(c)*Math.Pow(10, counter); } return (int)number%len; }
Reply | Email | Modify 
Email by Sheryl On July 19, 2011
Can you please email me at sherylkierstead@live.com? I need to use this class in a particular project and I need more info.
Reply | Email | Modify 
Re: Email by Mahesh On September 8, 2011
Class is a part of the .NET framework. Just copy the code :)
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.