-2

I have a 'for' loop that calls a method that returns a random number between 1 and 10. The loop then writes this number to the console. When I run the code normally it always returns the same number. However, when I step through the code with the debug tool everything seems to be working correctly; the method returns a different random number each loop cycle. What is going on?

   for(int i = 0; i < 5; i++)
        {
            int r = RandomNumber();
            Console.WriteLine(r);
        }

   static int RandomNumber()
        {
            Random rand = new Random();
            int x = rand.Next(1, 11);
            return x;
        }
  • Make your `rand` object a class field rather than a local variable inside the method, and only initialize it one time. – Rufus L Oct 02 '19 at 01:44

1 Answers1

2

You should create the “new Random” object just once when your application starts running.

Creating a new each time within the loop will result in a significantly less random sequence of numbers - including as you are seeing the exact same numbers, as Microsoft’s own docs say :

https://learn.microsoft.com/en-us/dotnet/api/system.random.-ctor?view=netframework-4.8

because the first two Random objects are created in close succession, they are instantiated using identical seed values based on the system clock and, therefore, they produce an identical sequence of random numbers.

When you step through with the debugger, you spend seconds stepping through, so the different instances of Random get created with different seeds.

racraman
  • 4,988
  • 1
  • 16
  • 16