0

Hey im trying to return a random number from a method. my code works, it returns a random number, but the problem is that its the same number it returns if i use it twice in the same while loop, how do i fix the problem? if there is a fix to the problem.

My code look like this

 private int ReturnARandomNumber(int min, int max)
 {
    var randomNumber = new Random();
    return randomNumber.Next(min, max);
 }

- Morten syhler

3 Answers3

2

You should move the declaration:

var randomNumber = new Random();

out of the method scope to the class scope:

var randomNumber = new Random();
private int ReturnARandomNumber(int min, int max)
{
    return randomNumber.Next(min, max);
}
Dmitry
  • 13,797
  • 6
  • 32
  • 48
1

Don't create a new Random object each time. Random uses the current time as the default seed, and if you call that function often in a tight loop, it's getting the same seed value on subsequent calls. Random works best if you re-use the same object over a period of time:

private Random randomNumber = new Random();
private int ReturnARandomNumber(int min, int max)
{     
    return randomNumber.Next(min, max);
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
-1

The seed used for the generation of random numbers is based for the current time. One way around that in your case is to let the Random be a parameter in the function, so that you can initialize it outside your loop.

fuglede
  • 17,388
  • 2
  • 54
  • 99