Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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:
Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads :
Total page views :  559667
Rating :
 5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor



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();
}


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of 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 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | Modify | 
Re: Good by Mahesh On March 13, 2007
No problem.
Reply | Email | Delete | 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 | Delete | Modify | 
c# by Nitin On April 13, 2007
how to generate serial no.using random function
Reply | Email | Delete | 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 | Delete | Modify | 
Re: Interesting by Mahesh On June 21, 2007
Good finding. Thanks M.
Reply | Email | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 
tell me code by Akhilesh On August 29, 2008
i want to generate random number without duplicate number. how its possible
Reply | Email | Delete | Modify | 
tell me code by Akhilesh On August 29, 2008
i want to generate random number without duplicate number. how its possible
Reply | Email | Delete | 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 | Delete | Modify | 
Re: akhi2485 by Mahesh On April 7, 2009
Please see my next comment.
Reply | Email | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved