It is because, if we will provide identical seed value, then we will get the identical sequence of random number numbers. If you want different numbers in sequence then use different seed values or use different Random objects.
But sometimes in testing we get this behavior even when we are having 2 different Random objects. This is because Random is time dependent and parameter less constructor uses the system clock to get seed. According to Microsoft - "
"
To overcome this situation I used a technique to generate a unique seed value every time. And same is implemented in below code:
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
for (int i = 0; i < 500; i++)
{
int len = 65;
Console.WriteLine(GenerateRandomKey(len));
}
}
private static string GenerateRandomKey(int charsCount)
{
char[] stringChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
StringBuilder sb = new StringBuilder(charsCount);
int seed = GetSeed();
Random rnd = new Random(seed);
for (int i = 0; i < charsCount; i++)
{
int ind = rnd.Next(0, 62);
sb.Append(stringChars[ind]);
}
string key = sb.ToString();
return key;
}
private static int GetSeed()
{
byte[] array = Guid.NewGuid().ToByteArray();
int seed = 0;
foreach (var item in array)
{
seed += item;
}
return seed;
}
}
Here to get seed I am using "Guid.NewGuid().ToByteArray()" function and adding their values to get a number. As GUIDs are always unique (99% of the time) so we will always get a unique seed value. And hence always a unique random sequence.