0
for (int i = 0; i < 20; i++)
{
    byte wtf = (byte) new Random().Next(10);
    Console.Write(wtf + " ");
}

This code produces the expected output if I run the program step by step: 4 6 9 2 9 0....

But if I just hit the Start Debugging or -Without Debugging this happen: 7 7 7 7 7 7...

Why?

Klorissz
  • 210
  • 2
  • 12

1 Answers1

2

Because your loop is happening too fast. The Random class uses the system clock for a seed, I believe, and when your loops run during the same millisecond, it gets the same seed.

Here's what you really need to do: instantiate Random outside of your loop:

var rand = new Random();

for (int i = 0; i < 20; i++)
{
    byte wtf = (byte) rand.Next(10);
    Console.Write(wtf + " ");
}
rory.ap
  • 34,009
  • 10
  • 83
  • 174