0

I'm getting some very strange behavior, please help!

I'm iterating through an object array, the participate property is a bool. The method randomly assigns each person a true or false (50/50 right now). As the code is right now, all five people either get all true or all false. When the message box is enabled, the code works properly (each person gets a true or false, not all the same)!!!!

for (int i = 0; i < 5; i++)
{
    //other code removed, I'll add it if it turns out to be important to the problem
    person[i].participate = doesPersonJoin();
}

public bool doesPersonJoin()
{
    bool joinBool = true;
    Random rnd = new Random();
    int r = rnd.Next(1, 100);
    //MessageBox.Show(r.ToString());
    if (r > 50)
    {
        joinBool = false;
    }
    return joinBool;
}
Ken Smith
  • 15
  • 2

1 Answers1

1

The random number generator works by setting a seed value based by default on the current clock time. Without MessageBox, the code runs so fast all of the random instances have the same seed and therefore produce the same value when .Next() is called.

To fix this, you should create ONE random instance you can use throughout your program, or at least one instance (possibly static) for use in that class.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • One instance for the class worked! Thanks so much! – Ken Smith Sep 19 '20 at 01:47
  • For the rest of time, remember this, as you will see it again in other forms - "if something works when you're slowly stepping through it in the debugger, but fails at full speed in production, your first suspicion should be a timing related issue" – Caius Jard Sep 19 '20 at 05:54