Hi. I'm new to C# and i'm facing this wierd thing. To put it simple i have two classes:
- Especimen
- Form1
Form1 has a button, when you click it it generates 10 objects of class Especimen. This is a very simple class, it's supposed to simulate a biological particle so, besides other irrelevant properties, it has an integer that indicates how old will it "die".
Through a textBox I indicate the "more or less" age i want them to die but i don't want them to die at the same time that's why i call this function from Especimen's constructor:
private int CalcularEdadFinal(int eF)
{
Random randNum = new Random();
diferencia = randNum.Next(0, 10);
if (diferencia % 2 == 0) return eF - diferencia;
else return eF + diferencia;
}
Easy! This will generate a number between 0 and 10 so when i say i want them to die at "more or less" 40 cicles, they will be dying when they are between 30 and 50 cicles, so it's more "natural" than dying all at the same time, right? OK!
This is the button1_click function:
private void button2_Click(object sender, EventArgs e)
{
iMaximoEspecimenes = int.Parse(tbMaximoEspecimenes.Text);
iMediaMortalidad = int.Parse(tbMediaMortalidad.Text);
List<Especimen> listaEspecimenes = new List<Especimen>();
for (int i = 0; i < iMaximoEspecimenes; i++)
{
listaEspecimenes.Add(new Especimen(iMediaMortalidad));
}
foreach (Especimen especimen in listaEspecimenes)
{
MessageBox.Show("Especimen nº " + listaEspecimenes.IndexOf(especimen) + "\n\nMorirá a los " + especimen.EdadFinal + " ciclos.\nPoblacion: " + Especimen.Poblacion + ".");
}
}
}
That's the code. When i run it, ALL objects have the same dying age, so weird. So I added a breakpoint in the function that generates the dying age and guess what, it works perfectly when debugging but not in a normal run. So it's like the function doesn't have enough time to generate different values everytime the constructor calls it (10 times in a row) but it does have the time to generate different values if i'm debugging the program (going instruction by instruction).
It also works fine if i add a MessageBox.Show("bla") in the for that fills the list with 10 objects, also giving time the generator to generate different numbers and not the same one everytime.
How can i fix this? Why does it seems to not work properly when working without stopping everytime i call this function?
Thank you! I hope i made this clear to read and solution, excuse my english.