2

Possible Duplicate:
Random number generator not working the way I had planned (C#)

I have a method which return 9 digit string number , if I call this method it works properly as I expected , But not when I call it in loop statement , Because it generate just one number and repeat it .

Here is the code :

private string GenerateRandomNumber()
        {
            Random r = new Random();
            return r.Next(111111111, 999999999).ToString();
        }
        protected void btnSolo_Click(object sender, EventArgs e)
        {
            Response.Write(GenerateRandomNumber());
            // Every time I call this method , it return 9 digit random number wich is different with the previous call like : 146956595  
        }
        protected void btnBulk_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                string randomNumber = GenerateRandomNumber();
                Response.Write("<br /> " + randomNumber);
                //It  create just one 9 digit number 100 times !
            }
        }
Community
  • 1
  • 1
Mark
  • 93
  • 6
  • 2
    This question explains why: [Random number generator not working the way I had planned (C#)](http://stackoverflow.com/questions/767999/random-number-generator-not-working-the-way-i-had-planned-c) – Dan J Aug 09 '12 at 19:24

2 Answers2

3

Make Random r = new Random(); be done at the class level, and save r as a class variable. Subsequent calls to Next won't generate the same "random" values.

private static Random r = new Random();

private string GenerateRandomNumber()
{
    return r.Next(111111111, 999999999).ToString();
}

protected void btnSolo_Click(object sender, EventArgs e)
{
    Response.Write(GenerateRandomNumber());
}

protected void btnBulk_Click(object sender, EventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        string randomNumber = GenerateRandomNumber();
        Response.Write("<br /> " + randomNumber);
    }
}
Dan
  • 9,717
  • 4
  • 47
  • 65
2

The GenerateRandomNumber() method uses the system clock as a seed.

That is, it performs a complex calculation on the current value of system clock as true randomness is not possible on a computer. The thing is CPUs are so fast that you may be running your loop and getting the same values because the time has hardly changed (if at all). Try looping for more iterations and see what happens, eventually the random value should change.

PaulG
  • 6,920
  • 12
  • 54
  • 98