-1

So im going through a tutorial where you call methods, and withing these methods you want to do use the Random(), in the tutorial he calls his method multiple times and get random results, but when I do it, i get the same result multiple times, all the time. Am I doing something wrong?

static void Main(string[] args)
        {
            MeetAlien();
            Console.WriteLine("---------------");
            MeetAlien();
            Console.WriteLine("---------------");
            MeetAlien();
        
        }

        static void MeetAlien()
        {
            Random numberGen = new Random();
            string name = "X-" + numberGen.Next(10, 9999);
            int age = numberGen.Next(10, 500);

            Console.WriteLine("Hi Im " + name);
            Console.WriteLine("Im " + age + " age old");
            Console.WriteLine("And im an alien :)");
        }
CptDubb
  • 31
  • 6

1 Answers1

4

That's a bad piece of sample code, if it's a faithful reproduction from a tutorial.

The problem is that it's repeatedly constructing Random objects without a seed. As the docs state:

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.

(It's talking about a different example, but the explanation is the same)


Further down, it's discussed that .NET Framework acts differently to .NET Core, so that indicates that you're running this code on .NET Framework. Maybe the tutorial is meant to be for .NET Core?

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448