Create better random numbers in C#

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):

RandomNumber.cs class

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.

9 thoughts on “Create better random numbers in C#

  1. I wrote a little C# app to test this with zero and found out for myself that it does indeed work.  Thanks for the code, it will make my language learning flashcard selection a little less predictable!  Good work.

    1. Hi,

      I’m sorry I couldn’t answer. I didn’t have Internet until last night. But you figured out the best way to see if it works. 🙂 Good luck with your language learning program!

  2. Thanks, this is a simpler approach than what I was using and so far it is working well for me.  Thanks for taking the time to post your code.

  3. Nice.  Also, if you know that you need to generate say 10,000 random number in advance (so they are available instantly), it is very easy to change the above code to return an array of 10,000 or whatever random numbers all at once.  This routine returns ‘amount’ of random numbers.  It is similar except I changed the maximumValue to be exclusive… so (zero to maximumValue – 1):


Leave a Reply

Your email address will not be published. Required fields are marked *