1
    static void Main(string[] args)
    {

        //random number gen
        Console.WriteLine("Array Random Number:");
        randomGenA();
        Console.WriteLine("------------------");

        //LIST: random movie picker...
        Console.WriteLine("List Random Number:");
        randomGenB();
        Console.WriteLine("------------------");

        Console.ReadLine();
    }

    static void randomGenA()
    {
        Random randomA = new Random();
        int randomNumA = randomA.Next(51);

        Console.WriteLine(randomNumA);

    }
    static void randomGenB()
    {
        Random randomB = new Random();
        int randomNumB = randomB.Next(0,51);

        Console.WriteLine(randomNum);
    }
 }

I wanted them both to produce two different random numbers but instead I keep getting the same random number from both of them. Why does it do this?

BlakeWebb
  • 479
  • 5
  • 11

2 Answers2

3

Declare a class level random and use it in your methods:

private static Random _random = new Random();

Your methods would look like:

static void randomGenA()
{
    int randomNumA = _random.Next(51);

    Console.WriteLine(randomNumA);

}
static void randomGenB()
{
    int randomNumB = _random.Next(0,51);

    Console.WriteLine(randomNum);
}

Check this out for further reading: http://www.dotnetperls.com/random

lintmouse
  • 5,079
  • 8
  • 38
  • 54
0

As per the documentation:

https://msdn.microsoft.com/en-us/library/system.random%28v=vs.110%29.aspx

Two Randoms with the same seed will provide the same sequence of numbers. Simply don't use the same seed. If you don't specify a seed, it uses the system time. Wait some time between the two instantiations and it will use two different system times.

Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37