Same random numbers from instantiated class

Posted by user1797202 on Stack Overflow See other posts from Stack Overflow or by user1797202
Published on 2012-11-03T22:42:22Z Indexed on 2012/11/03 23:00 UTC
Read the original article Hit count: 186

Filed under:
|

I'm learning C# and created a class within my program that holds a random number generator:

class RandomNumberGenerator
{
    Random RNG = new Random();
    // A bunch of methods that use random numbers are in here
}

Inside this class are a few methods that use the RNG. Data gets sent here from other parts of the program, gets processed, then gets returned. One of the methods does the following:

// Method works something like this
int Value1 = RNG.Next(x, y);
int Value2 = RNG.Next(x, y);
int Value3 = RNG.Next(x, y);

The x, y values are to be sent here from another class. So, I have to create an instance of the RandomNumberGenerator within that class so I can call its methods and pass the x and y values to it.

class DoStuff
{
    RandomNumberGenerator Randomizer = new RandomNumberGenerator
    // Here I call a bunch of Randomizer methods that give me values I need
}

The problem in the above method is that I get the same numbers every time for all three values. I'm not sure if it's because they're so close together and Randomizer's seed value hasn't had time to change or if I'm doing something wrong when I create a new instance of the RandomNumberGenerator class.

I've gone through a bunch of answers on here already and typically problems like this are due to people creating many new Random objects when they run methods (thus setting the seed for all of them to the same value), but the only new Random object I create is within the RandomNumberGenerator class. I then instantiate that once within the other class so I can pass it data and use its methods.

Why is this happening and how would I fix this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about random