Alex Rivera | Logout

Why does Random.Next() always return the same number

Asked 2011-03-10T18:58:32.597
25

Consider this method:

private static int GenerateRandomNumber(int seed, int max)
{
   return new Random(seed).Next(max);
}

On my machine, executing this loop yields the same number through 1500 iterations:

  for (int i = 0; i < 1501; i++)
            {
                int random = GenerateRandomNumber(100000000, 999999999);
                Console.WriteLine(random.ToString());
                Console.ReadKey();
            }

I get 145156561, for every single iteration.

I don't have a pressing issue, I was just curious about this behavior because .Next(max) says "Returns a Non Negative random number less than the specified maximum. Perhaps I am not understanding something basic.

Edit
Report

1 Answer

49

You're always seeding a new instance with the same seed, and then grabbing the first max. By using a Seed, you're guaranteeing the same results.

If you want to have a static, random number generation that does different results, you should rework this a bit. However, since Random is not threadsafe, it requires some synchronization when used statically. Something like:

private static Random random;
private static object syncObj = new object();
private static void InitRandomNumber(int seed)
{
     random = new Random(seed);
}
private static int GenerateRandomNumber(int max)
{
     lock(syncObj)
     {
         if (random == null)
             random = new Random(); // Or exception...
         return random.Next(max);
     }
}
answered 2011-03-10T19:00:01.563

Your Answer