Random number in a loop [duplicate]

Move the declaration of the random number generator out of the loop.

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, …

Source

By having the declaration in the loop you are effectively calling the constructor with the same value over and over again – hence you are getting the same numbers out.

So your code should become:

Random r = new Random();
for ...
    string += r.Next(4);

Leave a Comment