Silverlight Tip of the Day #77 - Creating an Efficient Random Generator
In some of my older posts I was creating a separate random generator for each object. However, the documentation on Random states:
"The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers."
As a result I created a single random generator class and I put it in a new static class called Utils where it could be globally referenced.
public class Utils
{
static Random _random;
static Utils()
{
_random = new Random();
}
public static int RndGen(int min, int max)
{
return _random.Next(min, max);
}
}
To make a call now from one of your classes such as your Page class you simply make a call like this to get a random number:
int value = Utils.RndGen(1, 50);
The first parameter is the minimum value you want, the second is the maximum.
I updated Tip of the Day #43 - Snowflake scene - to use this implementation.
Thank you,
--Mike Snow
Subscribe in a reader