I found this snippet of code that generates a string of random characters.
But is there a more elegant/faster/more reliable way to do this? This seems to rely on the fact that the numbers 26-91 are valid characters given the current encoding.
/// <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();
}
I’d prefer to pass the
Randominstance into the method – then you can reuse the same instance multiple times, which is important if you need to generate lots of random strings in quick succession. However, I’d also modify it somewhat anyway:Random.NextDouble()indicates a lack of knowledge of the Random class. (In particularRandom.Next(int, int)