In this article, we are going to learn How to Generate Random Numbers in C#. C# provides us a class to generate random numbers that is named “Random”. In random class, we can use the predefined method “Next()” to generate random numbers and numbers within a self-defined range.
Let’s move forward to code to see how does this class works.
To use Random class and access its methods we have to initialize first the “Random” class with the new Keyword and after initializing e can access its members by its constructor.
var random = new Random(); int num = random.Next(); Console.WriteLine(num); Console.ReadLine();
The above code will generate a random between −2,147,483,648<=value<=2,147,483,647 this range. We can also define the minimum and maximum ranges by overloading the “Next()” method.
Now let’s see how can we generate random numbers between self-defined ranges.
int min = 5000; int max = 6000; var random = new Random(); int num = random.Next(min,max); Console.WriteLine(num); Console.ReadLine();
We can also specify the number of digits we want in random numbers by changing the minimum and maximum digits count.
Let’s discuss another method to generate random numbers in C#. We can use “RandomNumberGenerator.GetInt32()” class to generate random integers it’s a static class so we do not have to initialize it first. “RandomNumberGenerator.GetInt32()” generates a random integer between a specified inclusive lower bound and a specified exclusive upper bound using a cryptographically strong random number generator.
int lowerbound = 5000; int upperbound = 6000; var num = RandomNumberGenerator.GetInt32(lowerbound,upperbound); Console.WriteLine(num); Console.ReadLine();
Conclusion:
In this tutorial, we have learned two different ways of how to generate random numbers in C#. If you have any suggestions to improve this post or have any queries or concerns feel free to ping us at Contact.