Why Random generates different numbers in loop?

Hello there I want to generate random numbers, so I created method in my class

        private readonly Random _rand = new Random(); //Private property of class

        public void GenerateRandomNumber()
        {
            //For loop executes 10 times
            for (int i = 1; i < 11; i++)
            {
                Console.WriteLine(_rand.Next(0, 10));
            }
        }

When I call this from Main I create new instance of my class and then call it. It works properly but I want to know why does this generate different numbers each time in for loop and also each time I run the program?

That’s interesting for me because I know that Random can generate same numbers but in my case it generates different ones.

How will it affect if I add static modifier to private property?

>Solution :

In C# your random number generator will automatically set the seed to a value based on your system clock, thus generating pseudo random numbers. If you would like your random numbers to be in the same order every time you run the program you can manually set the seed using:

seed = 999
private readonly Random _rand = new Random(seed)

Leave a Reply