LaTachuela
LaTachuela

Reputation: 11

Need to generate different random numbers

I need help in trying to generate a random number because with my coding below it shows the same number in both text boxes.

   private int RandomNumber(int min, int max)
{

    Random random = new Random();
    random.Next();
    return random.Next(1, 7); // random integer and assigned to number  
} 


private void button1_Click(object sender, EventArgs e)
{


    tb1.Text = RandomNumber(1, 7).ToString(); // Random Number for Text Box 1.
    tb2.Text = RandomNumber(7, 1).ToString(); // Random Number for Text Box 2.

}

Upvotes: 0

Views: 72

Answers (3)

Jamie Dixon
Jamie Dixon

Reputation: 53991

You need to create the Random object outside of your function. Creating a new one each time you need a new random number will result in the seed being identical (given the time gap between creations)

Upvotes: 0

SLaks
SLaks

Reputation: 887225

Random picks a seed based on the current time.
If you create two Randoms at the same time, they will give you the same numbers.

Instead, you need to create a single Random instance and store it in a field in your class.

However, beware that Random is not thread-safe.

Upvotes: 3

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107498

You need to instantiate your Random class only once. From MSDN, the documentation states that:

If the same seed is used for separate Random objects, they will generate the same series of random numbers.

In your case, as SLaKs also said, the seed is the current time. You're calling the functions so close together they are using the same seed. If you move the instantiation outside of the function, you have one instance based on one seed, instead of multiple objects based on the same seed.

Random random = new Random();

private int RandomNumber(int min, int max)
{
    return random.Next(1, 7); // random integer and assigned to number  
} 

Upvotes: 1

Related Questions