I was digging around in an old program I wrote and saw a method I wrote for random number generation. It reminded me that some programmers may not realize the problem with the normal random number code in .Net – and how the numbers are actually predictable.
If you use the System.Random class, and create new instance of it with every use, you’ll get the same numbers, in the same order.
To see the problem, run a program that uses a System.Random object to generate 10 random numbers. Write those numbers down, and then stop the program. Now, run the program again. You’ll see that it gives you the same 10 numbers, in the exact same order.
This happens because the random number generator initializes itself with a seed value. But it’s the same seed value each time you run the program. So, you get the same results. This is often called “pseudo-random” numbers.
A better method is to use the random number generator in the cryptography library of the .Net framework. It may not be a 100%, true random number (if you want to get into high-level mathematics), but it’s good enough for almost anything most of us will ever need.
Here’s the code I used to create a random number between two numbers (inclusive):
public static class RandomNumber
private static readonly RNGCryptoServiceProvider _generator = new RNGCryptoServiceProvider();
public static int Between(int minimumValue, int maximumValue)
byte randomNumber = new byte;
double asciiValueOfRandomCharacter = Convert.ToDouble(randomNumber);
// We are using Math.Max, and substracting 0.00000000001,
// to ensure "multiplier" will always be between 0.0 and .99999999999
// Otherwise, it's possible for it to be "1", which causes problems in our rounding.
double multiplier = Math.Max(0, (asciiValueOfRandomCharacter / 255d) - 0.00000000001d);
// We need to add one to the range, to allow for the rounding done with Math.Floor
int range = maximumValue - minimumValue + 1;
double randomValueInRange = Math.Floor(multiplier * range);
return (int)(minimumValue + randomValueInRange);
The reason this method has minimumValue and maximumValue parameters was because I needed to be able to generate a random number between 5 and 10 (for example).
So, if you’re creating a .Net game, or any other .Net program where you want to have something randomized, use a method like this to give you better random results.
EDIT: 28 Apr 2014
I moved the generator variable to a static class-level variable, so we don’t keep creating new instances of this object – or need to worry about disposing them.