Why does it appear that my random number generator isn't random in C#?
How can I generate truly (not pseudo) random numbers with C#?
public static void Roll()
Random rand = new Random((int)DateTime.Now.Ticks);
return rand.Next(1, 100);
for (int i = 0; i < 5; i++)
Console.WriteLine("#" + i + " " + Roll());
DateTime.Now.Ticks only has a resolution of approximately 16ms, so if you create a
Random with that overload multiple times within a 16ms "slot" they will all be seeded with the same value and therefore you will get the same sequence.
Random outside your loop so that a single
Random sequence is produced, rather than creating it each time within the loop which could result in
Randoms being seeded with the same value and so produce the same sequence.
My previous point that the default constructor initialized
Random with CPU ticks was incorrect, the default constructor actually uses Environment.TickCount which is:
A 32-bit signed integer containing the amount of time in milliseconds that has passed since the last time the computer was started.
Which still has a low resolution. If you make multiple instances of
Random in quick succession, they can easily be created within the same time slot and therefore have the same seed value, and create the same sequence. Create a single instance of
Random and use that.
Further to your comments, if you wish to generate a random sequence across multiple threads, please see the following Jon Skeet article which discusses a thread-safe wrapper: