How to: Get random numbers (Random() & RNGCryptoServiceProvider())

For use with simple, everyday projects where you might need a simple random number, Random() should be enough.

The only thing that you need to make sure when using Random() is that, if you fail to use it correctly, you might end up getting the same number time and again.

What you need to keep in mind is that you will need to:

Avoid creating local Random() instances. Always use Random() as a member variable.

Keeping this in your code:

static Random rnd = new Random();

will make sure that your seed is initialised once and then, each time you call rnd.Next() you will get a different number.

If you want a random number for use with cryptography (or, for any other reason you might need a more reliable random number generator) you will need to use the RNGCryptoServiceProvider() provider.

You need a “using System.Security.Cryptography;” and then,

using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
// Buffer storage.
byte[] data = new byte[4];

        // Ten iterations.
for (int i = 0; i < 10; i++)
{
// Fill buffer.
rng.GetBytes(data);

        // Convert to int 32.
int value = BitConverter.ToInt32(data, 0);
Console.WriteLine(value);
}
}

Do note that the RNGCryptoServiceProvider will take significantly longer than Random() to provide you with a random number.

For more detailed information, visit the excellent dotnetperls.

Random()

RNGCryptoServiceProvider

MGR: the Intelogist

About MGR: the Intelogist

SharePoint Server developer, turned Sitefinity developer, turned Angular developer, turned SharePoint Online consultant, turned Unily consultant, turned O365 consultant... Never a dull moment!

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

This site uses Akismet to reduce spam. Learn how your comment data is processed.