This post will discuss how to generate a random number between the specified range in C#.

1. Using Random Class

We can use the Random.Next() method that generates a pseudorandomly random value between the specified range. The following code uses the Random.Next() method to generate a random integer between min and max.

Download  Run Code

2. Using RNGCryptoServiceProvider Class

The Random class is not cryptographically secure. To generate a cryptographically secure random value, use the RNGCryptoServiceProvider class or derive a class from System.Security.Cryptography.RandomNumberGenerator.

The RNGCryptoServiceProvider class uses System entropy for generating seeds. Its usage is demonstrated below:

Download  Run Code

That’s all about generating a random number in C#.