Possible Duplicate:
Random number generator only generating one random number
My code below is doing this and I don’t know why:
IF my toEmailAddresses array contains 2 e-mail addresses, uniqueID[0] and uniqueID[1] will return the same value generated from the Util.CreateRandomPassword(16) method call.
If I step through the code, then both uniqueID[0] and uniqueID[1] will contain different values like it should. But if I run the code as usual, for some reason, the same value gets assigned to my uniqueID array: uniqueID[0] and uniqueID[1] will contain the same value.
I even put in the string tempRandomPassword = null and then assign that to the value returned from the CreateRandomPassword method, but that does not work either.
What am I doing wrong?
//toEmailAddresses.Count array will have two e-mail addresses in it.
string[] uniqueID = new string[2];
for (int i = 0; i < toEmailAddresses.Count(); i++)
{
string tempRandomPassword = null;
tempRandomPassword = Util.CreateRandomPassword(16);
uniqueID[i] = tempRandomPassword;
}
public static string CreateRandomPassword(int passwordLength)
{
//http://madskristensen.net/post/Generate-random-password-in-C.aspx
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
char[] chars = new char[passwordLength];
Random rd = new Random();
for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}
You’re creating a new instance of
Randomwith the default seed on every invocation. If the seed is the same it will produce the same sequence of numbers. Store the instance and use that for all invocations.