Possible Duplicate:
c# random string generator
I need to generate a random string with a given length. This is my code so far. The problem is the random string is like "RRRRRR" or "SSSSS" The same letter every time. Just when i restart the app the letter change. I need something like "asrDvgDgREGd"
public string GenerateChar()
{
Random random = new Random();
return Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))).ToString();
}
public string GenerateChar(int count)
{
string randomString = "";
for (int i = 0; i < count; i++)
{
nahodneZnaky += GenerateChar();
}
return randomString;
}
Try using the same random object for the whole string, rather than initializing one for each char.
The random object will generate a "pseudo-random" number, based on mathematical progressions starting from a "seed" number. You can actually get the same sequence of "random" numbers if you initialize the Random object to the same seed every time.
Now, when you initialize Random without specifying a seed, it'll take the computer's clock as seed. In this case, you're probably doing it fast enough that the clock hasn't changed from one initialization to another, and you get always get the same seed.
You're better off initializing the Random object in your function that generates the random string, and passing it as a parameter to the GenerateChar function, so that you're calling NextDouble() several times on the same instance of the Random object, instead of only once on different instances of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With