Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Generating Random String in C#.

Posted by Viral Sarvaiya on May 14, 2012

.Net provide Random class to generate random number.
Here generating random string.

private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

private string RandomString(int size)
{
char[] buffer = new char[size];

for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}

Thanks.

Advertisements

2 Responses to “Generating Random String in C#.”

  1. Jeff Moden said

    You might want to remove the vowels from all of that or you stand the chance of spelling some pretty offensive swear words. 😉

  2. Viral Sarvaiya said

    Thanks for notifying me for that.. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: