How do I generate a random int number?


How do I generate a random integer in C#?

3/6/2019 10:20:38 AM

Accepted Answer

The Random class is used to create random numbers. (Pseudo-random that is of course.).


Random rnd = new Random();
int month  = rnd.Next(1, 13);  // creates a number between 1 and 12
int dice   = rnd.Next(1, 7);   // creates a number between 1 and 6
int card   = rnd.Next(52);     // creates a number between 0 and 51

If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

3/17/2019 11:05:16 AM

The question looks very simple but the answer is bit complicated. If you see almost everyone has suggested to use the Random class and some have suggested to use the RNG crypto class. But then when to choose what.

For that we need to first understand the term RANDOMNESS and the philosophy behind it.

I would encourage you to watch this video which goes in depth in the philosophy of RANDOMNESS using C#

First thing let us understand the philosophy of RANDOMNESS. When we tell a person to choose between RED, GREEN and YELLOW what happens internally. What makes a person choose RED or YELLOW or GREEN?

c# Random

Some initial thought goes into the persons mind which decides his choice, it can be favorite color , lucky color and so on. In other words some initial trigger which we term in RANDOM as SEED.This SEED is the beginning point, the trigger which instigates him to select the RANDOM value.

Now if a SEED is easy to guess then those kind of random numbers are termed as PSEUDO and when a seed is difficult to guess those random numbers are termed SECURED random numbers.

For example a person chooses is color depending on weather and sound combination then it would be difficult to guess the initial seed.

c# Random

Now let me make an important statement:-

*“Random” class generates only PSEUDO random number and to generate SECURE random number we need to use “RNGCryptoServiceProvider” class.

c# Random

Random class takes seed values from your CPU clock which is very much predictable. So in other words RANDOM class of C# generates pseudo random numbers , below is the code for the same.

**Note: ** .NET Core 2.0.0+ uses a different seed on the parameterless constructor: instead of CPU clock it uses Guid.NewGuid().GetHashCode().

var random = new Random();
int randomnumber = random.Next()

While the RNGCryptoServiceProvider class uses OS entropy to generate seeds. OS entropy is a random value which is generated using sound, mouse click, and keyboard timings, thermal temp etc. Below goes the code for the same.

using (RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider()) 
    byte[] rno = new byte[5];    
    int randomvalue = BitConverter.ToInt32(rno, 0); 

To understand OS entropy see this video from 14:30 where the logic of OS entropy is explained. So putting in simple words RNG Crypto generates SECURE random numbers.


Every time you do new Random() it is initialized . This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

//Function to get random number
private static readonly Random getrandom = new Random();

public static int GetRandomNumber(int min, int max)
    lock(getrandom) // synchronize
        return getrandom.Next(min, max);

Beware that new Random() is seeded on current timestamp.

If you want to generate just one number you can use:

new Random().Next( int.MinValue, int.MaxValue )

For more information, look at the Random class, though please note:

However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers

So do not use this code to generate a series of random number.


Random r = new Random();
int n = r.Next();

I wanted to add a cryptographically secure version:

RNGCryptoServiceProvider Class (MSDN or dotnetperls)

It implements IDisposable.

using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
   byte[] randomNumber = new byte[4];//4 for int32
   int value = BitConverter.ToInt32(randomNumber, 0);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]