Generate a random number in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { int min = 1; int max = 10; Random rnd = new Random(); Console.WriteLine(rnd.Next(min, max + 1)); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Security.Cryptography; public class Example { public static int GetRandomNumber() { using (RNGCryptoServiceProvider rngCrypt = new RNGCryptoServiceProvider()) { byte[] tokenBuffer = new byte[4]; // `int32` takes 4 bytes in C# rngCrypt.GetBytes(tokenBuffer); return BitConverter.ToInt32(tokenBuffer, 0); } } public static void Main() { int random = GetRandomNumber(); Console.WriteLine(random); } } |
That’s all about generating a random number in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)