That code is bad to begin with - RNG algorithms use the previous N values to generate random numbers with good randomness characteristics.
Unless a seed is provided, most RNGs will use something like the processors' tick count or clock, which is a strictly incrementing number as the seed. This alone reduces the randomness of the generated numbers. That's why some cryptographic tools require you to move the mouse around to generate a random initial sequence. Simplistic implementations may even use a hard-coded seed.
That said, the processor's clock has a finite resolution. If the loop executes quickly enough, several RNG objects may end up receiving the same seed value.
You'll get into the same problem if you try to implement a sequential GUID algorithm using the tick count instead of using Windows API's functions.
The correct way to generate good random numbers is to create Random
once and reuse it :
var rnd = new Random();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(rnd.Next(10));
}
If on the other hand you want to generate reproducible number sequences for use eg in data science experiments, you need to specify the seed explicitly :
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
var rnd = new Random(1023);
Console.WriteLine(rnd.Next(10));
}
This produces 1
consistently, even though there's a delay
Update
.NET 4.8 still has this bug. The code still uses the processor count even in .NET Old 4.8 :
public Random()
: this(Environment.TickCount) {
}