In this blog post, we will see how we can create a random number or a random integer in C#.
Why Do We Need Random Numbers
Random numbers are of great use in a website and application. Using random numbers we can create a custom order of events everytime.
Random numbers can also be used in a game to pick the starting player or a creating a dice roll. The possibilities are endless.
Create a Random Number or Integer Using C#
C# gives us a class called Random that gives us a really easy way to create random numbers in between a range of 2 numbers (min and max). If no range is provided, the integer min and integer max values are taken.
Note: The returned number or integer can be greater than or equal to min value but less than max value.
Creating a Random Number (No values provided)
// Instantiating the Random class var random = new Random(); // Calling the next method in the Random class var randomNumber = random.Next(); Console.WriteLine(randomNumber.ToString()); // Result: 254896 (A random number)
Creating a Random Number (Only Max Value Provided)
// Instantiating the Random class var random = new Random(); // Calling the next method in the Random class var randomNumber = random.Next(99); Console.WriteLine(randomNumber.ToString()); // Result: 7 (A random number)
Creating a Random Number (Min and Max Values Provided)
// Instantiating the Random class var random = new Random(); // Calling the next method in the Random class var randomNumber = random.Next(20, 30); Console.WriteLine(randomNumber.ToString()); // Result: 29 (A random number)