1

I made a simple WindowsFormsApplication but I have some difficulties with it. In the form I have 10 TextBoxes and a button. The purpose of the program is to generate a different number in every single box when I click the button. Here is a part from the code:

private void button1_Click(object sender, EventArgs e)
    {
        int p = 0;
        int[] array = GeneratingArray();

        foreach (Control c in tableLayoutPanel1.Controls)
        {
            if (c.GetType().ToString() == "System.Windows.Forms.TextBox")
            {
                c.Text = array[p].ToString();
                p++;
            }
        }
    }

    public int GeneratingInt()
    {
        int random;
        Contract.Ensures(Contract.Result<int>() > -11, "Array out of Bounds(-10 ; 10)");
        Contract.Ensures(Contract.Result<int>() < 11, "Array out of Bounds(-10 ; 10)");
        Random gnr = new Random();
        random = gnr.Next(20);
        return random;
    }

    public int[] GeneratingArray()
    {
        int[] array = new int[10];
        int random;
        for (int i = 0; i < 10; i++)
        {
            random = GeneratingInt();
            array[i] = random;
        }

        return array;
    }

The problem is that when I use the debugger all works fine but when I start the application in all the boxes is generated the same number. I can't find what causes this kind of problem so I'm asking you. Thanks.

Hristo Angelov
  • 1,019
  • 1
  • 15
  • 34

1 Answers1

6

The problem is that your application is running to fast.

By creating a new instance of Random every call to GeneratingInt, you're seeding the random with the current time. When run in a tight loop, this causes the random generator to provide the same number every time.

Move your Random to a class level variable, construct it one time, and reuse the same instance. This will cause it to behave the way you wish.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Or he can be stubborn and pass the DateTime.Now.Ticks as a seed in the Random constructor parameter :) Not a good idea though. – Nyuno Dec 15 '12 at 20:22
  • Thanks a lot. That was the problem. – Hristo Angelov Dec 15 '12 at 20:23
  • 1
    @Nyuno You'll potentially get the same problem. The default constructor uses Environment.TickCount, but on XP, for example, this can have the same precision as DateTime.Now.Ticks. For details, see this great answer: http://stackoverflow.com/a/8865560/65358 – Reed Copsey Dec 15 '12 at 20:26
  • That's a great answer indeed. Thank you! – Nyuno Dec 15 '12 at 20:30