Friday, January 14, 2011

Everything just random?

Today I had to fix some code of a colleague. To test the class I've fixed, there was a mock class generating random testdata. But this testdata were always the same. So I looked also at this problem and found the following code:

for (int i = foo; i < bar; i++)
{
return new Random().Next();
}

Looks good at first glance, but this will always return the same number (at least in the same second). This is because the Random class uses in the default constructor a time-dependent default seed value.

An easy way to fix the problem would be to use the overloaded constructor and provide a unique seed value. For example just the int value i used for the for loop. This could look like:

for (int i = foo; i < bar; i++)
{
return new Random(i).Next();
}

Another way to get random numbers would be in using the Next method in a correct way. This meens on the same instance of the Random class. In this case the initialization of the Random class has to be outside the loop. The code would look like this:

var r = new Random();
for (int i = foo; i < bar; i++)
{
return new r.Next();
}

This way would definitely be better, then we need just one instance of the Random class.

Further information on the Random class can be found here http://msdn.microsoft.com/en-us/library/system.random.aspx.

No comments: