Friday, September 12, 2008

Random string generation in C#

I needed test data for one of my systems, so I put together a console app which generates random strings.


private static System.Random random = new System.Random((int)(System.DateTime.Now.Ticks % System.Int32.MaxValue));

static void Main(string[] args)
{
for (int i=0; i<10; i++)
{
Console.WriteLine(GetRandomString(5));
}
Console.ReadLine();
}

private static string GetRandomString(int length)
{
char[] returnValue = new char[length];
returnValue[0] = GetRandomUpperCaseCharacter();
for (int i = 1; i < length; i++)
{
returnValue[i] = GetRandomLowerCaseCharacter();
}
return new String(returnValue);
}

private static char GetRandomLowerCaseCharacter()
{
return ((char)((short)'a' + random.Next(26)));
}

private static char GetRandomUpperCaseCharacter()
{
return ((char)((short)'A' + random.Next(26)));
}


The key to getting random data is to initialize a Random object once with a value from the system clock (DateTime.Now.Ticks), and then to use the Next method each time you need a new random value.

If you create a new Random object each time you actually need a random number, chances are the clock will not have moved on, so you'll get repeated values until it does.

Thanks to:
http://www.developerfusion.co.uk/show/3940/