When I step through the program using the debugger it works fine and the displays the correct results. However, when I run the program it displays some extremely high number for
You are creating a new instance of the Random
class on each iteration of your loop. The documentation for the constructor you are using says:
Initializes a new instance of the Random class, using a time-dependent default seed value.
As the loop executes very quickly when you aren't debugging you end up with the same seed being used on many iterations and thus the call to Next
returns the same value each time. If that value happens to be a value that will increment the score then the score will be incremented on many iterations of the loop.
Moving the line
Random rnd1 = new Random();
above your for
loop will construct one Random
instance and then create a new random number for each call to Next
.
You can't reproduce this when running in the debugger as the clock has moved on by the time you create a new Random
instance and thus the seed has changed.
More information on the Random
instance returning the same value can be found in this StackOverflow post. Also, Jon Skeet has a blog post covering pitfalls when using the Random class which is well worth a read.