Reputation: 155
// in general i take random colors from an Enum and insert that into a new array. when i ask by BoxMessage inside the loop For each Array[i] i get random colors as expected. If i comment (\) the message box and ask for Array[1-5] outside the loop, i get the same color for all 5 message box. I believe it related to the fact that my message box inside the loop successfully convert the Enum into a string, when i tried to convert the whole array in the loop ( array[i].ToString(); ) it didn't quite work. please advise....
public void GetArray()
{
array = new EnumColor[5];
for (int i = 0; i < 5; i++)
{
rnd = new Random();
int rndnum = rnd.Next(0, 4);
array[i] = (EnumColor)rndnum;
MessageBox.Show(array[i].ToString());
}
MessageBox.Show(array[0].ToString());
MessageBox.Show(array[1].ToString());
MessageBox.Show(array[2].ToString());
MessageBox.Show(array[3].ToString());
MessageBox.Show(array[4].ToString());
}
Upvotes: 0
Views: 126
Reputation: 3702
The problem is indeed the Random being re-created for every loop. But here's the full explanation.
When you create a Random, it uses the Environment.TickCount as seed value. (milliseconds since system startup). So if your loop is fast enough, this will always be the same value, so the rnd.Next function will always return the same value.
So now for the tricky part.. why did it work with the messagebox inside the loop? By showing the message, the loop became slower by waiting for you clicking the ok button. Therefore the next loop, the seed was indeed changed. That's why you got another value.
Upvotes: 0
Reputation: 155433
for (int i = 0; i < 5; i++)
{
rnd = new Random();
int rndnum = rnd.Next(0, 4);
array[i] = (EnumColor)rndnum;
MessageBox.Show(array[i].ToString());
}
You're overwriting elements in the array, don't do this.
Retrieve elements into a temporary local variable instead (and use .Length
instead of a hardcoded length)
The bug itself is caused by Random
being incorrectly seeded, it's being regerated on every iteration.
Random rnd = new Random();
for (int i = 0; i < array.Length; i++)
{
int rndnum = rnd.Next(0, 4);
EnumColor selected = (EnumColor)array[i];
MessageBox.Show( selected .ToString() );
}
Upvotes: 1
Reputation: 101701
You are getting the same color because you are declaring random
instance each time in your loop, just move the declaration outside:
rnd = new Random();
for (int i = 0; i < 5; i++)
{ ... }
If you like to learn more about why Random
class works that way you can take a look at this answer.
Upvotes: 1