0

please could you explain why during complier we have randomly generated value - but the same for total array but during debugger it shows that for each element it's a randomly genereated value. For example:

static void Main(string[] args)
    {
        int[,] vs = new int[3, 4];
        //Random random = new Random();  // 1st example here random works ok in compiler
        for(int i = 0; i < vs.GetLength(0); i++)
        {
            for(int j = 0; j < vs.GetLength(1); j++)
            {
                Random random = new Random(); // 2nd example here value is random but the same for total array but during debugger it shows different result - each value in materix is randomly generated
                vs[i, j] = random.Next(100);
                Console.Write("{0,4}", vs[i, j]);
            }
            Console.WriteLine();
        }
        Console.ReadKey();
    }

I don't understand why, for example in first example it's:

  1. 12 43 2 51
  2. 3 5 1 4
  3. 12 99 42 12

In second example random place:

  1. 47 47 47 47
  2. 47 47 47 47
  3. 47 47 47 47

but if I use the debugger it shows me randomly generated each time like in the first exmaple? How to understand that?

Heron
  • 329
  • 2
  • 5
  • 15
  • Never create `Random` inside of a loop. It will be seeded with the current `DateTime` and the loop can run faster than the `DateTime` will change. – juharr Aug 07 '19 at 19:07
  • 1
    Probably a timing issue - when running at full speed the Random will be initialized over and over in the same millisecond and if it's seeded from the clock it will generate the same first random. When running in debug it's very slow step by stepping and will be seeded with a different clock value. For more info check the manual for how a random is seeded. Your commented out declaration is correct; declare one random and repeatedly use it, don't repeatedly renew it. – Caius Jard Aug 07 '19 at 19:09
  • See https://learn.microsoft.com/en-us/dotnet/api/system.random.-ctor?view=netframework-4.8 where it goes into detail how the random is seeded based on time and produces identical values – Caius Jard Aug 07 '19 at 19:13

0 Answers0