I was searching for answer, but couldn't find anything, so:
I am making simple project and I have a problem with this:
// fragment of code in parent form
Random r = new Random();
private void BeginGame()
{
SetName();
sheep = new Sheep[howManySheep];
for (int i = 0; i < howManySheep; i++)
sheep[i] = new Sheep(this);
(...)
}
public Sheep DrawSheep
{
set
{
splitContainer1.Panel2.Controls.Add(value);
}
}
// fragment of code in child form
class Sheep : Button
public Sheep(Form1 _parent)
: base()
{
var p = new Point(r.Next(_parent.PanelSize[0]), r.Next(_parent.PanelSize[1]));
Text = null;
Size = new Size(size, size);
BackColor = Color.White;
Tag = nrSheep++;
Location = p;
_parent.DrawSheep = this;
MessageBox.Show(this.Location.ToString());
}
While MessageBox.Show(..) is commented it draws only one sheep( I mean all of them, but in the same place) When MessageBox.Show(..) is uncommented it draws everything fine, how it's supposed to be. My question is how?
This sounds like a rather common problem with Random
. It usually goes away when you make it a class level variable:
public static Random r = new Random();
Usually one needs only one single Random
generator, which calls for making it static.
But why did the MessageBox
help?
The problem most often arises when instead of keeping a single static instance of a Random
you create fresh instances in quick succession. This can happen so fast, that they get the same default seed, derived from current time and so will create the same sequence of numbers.
Now, showing a MessageBox
lets a lot of time pass between the creation of the new Random
instances, so the problem seems to be solved but really is just hidden..
One other even more devious way of hiding this (and other time related problems) it is using the debugger - but don't let that keep you from using it ;-)