-2

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?

WideWood
  • 549
  • 5
  • 13
  • 3
    One look at the documentation tells you that you can seed the new Random with a number to create a repeatable sequence of numbers. – TaW Nov 25 '21 at 21:40
  • Even a superficial search would reveal this very old, very very active post:[Random number generator only generating one random number](https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number). – Ňɏssa Pøngjǣrdenlarp Nov 25 '21 at 22:18
  • @ŇɏssaPøngjǣrdenlarp not quite I wanted to know why Random made different values in my case. And now I know why, that's because I didn't pass `seed` parameter to constructor. – WideWood Nov 25 '21 at 22:22

2 Answers2

2

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)
Erik McKelvey
  • 1,650
  • 1
  • 12
  • 23
1

The Random object is not what's generating the numbers. When calling _rand.Next(0, 10), it's generating a random number between 0 and 9 which is why you are getting new numbers each time. See the documentation for Random.Next(). If you only want one random number, you will need to call this method outside of the loop and store the result in a variable.

Jesse
  • 1,386
  • 3
  • 9
  • 23