Random sometimes, not random other times

May 19, 2006 at 11:43 am

From a email:


private void button1_Click(object sender, EventArgs e)
{
   Customer c = new Customer();
   c.Randomize();


   Customer b = new Customer();
   b.Randomize();


   MessageBox.Show(string.Format(
        “object c random number = {0}, object b random number = {1}”,
        c.RandomNumber, b.RandomNumber));
}


public class Customer
{
   private int random = 0;


   public void Randomize()
   {
      Random r = new Random();
      random = r.Next();
   }


   public int RandomNumber
   {
      get { return random; }
   }
}


If I run the above code without debugging it always returns the same random number, but if I step through the code I get different random numbers.


******


This is a variant of a question that comes up fairly often.


When you create an instance of the Random class, the pseudo-random number generator needs to be seeded with an initial value. Some generators always seed with zero, which means you always get the same sequence of numbers. The .NET Random class seeds using the time, which means you get different results from run to run without having to set the seed yourself.


It also means, however, that if you create two Random instances one right after another, the seed value (I think it uses GetTickCount()) hasn’t had time to change, and you get the same sequence. But if you run it in the debugger, enough time passes between the creation of the two instances that you get different seeds and different numbers.


I think the best solution here is to move the Random instance to a static field:


static Random r = new Random();


And then just use that instance of Random from all the Customer instances.