This post will discuss how to generate a random number in a range using C#.

1. Using Random.Next() method

The Random.Next() method is commonly used to generate a pseudo-random random integer between the specified range. Its usage is demonstrated below:

Download  Run Code

 
Note that the minValue is inclusive, and maxValue is exclusive. If minValue is skipped, the Next() method returns a non-negative random integer that is less than maxValue.

Download  Run Code

2. Using Random.NextDouble() method

If you need to generate a random floating-point number in a range, consider using the Random.NextDouble() method instead. It returns a random floating-point value greater than or equal to 0.0, but less than 1.0. This method can be extended to generate values in any range, as shown below:

Download  Run Code

 
If minValue is skipped, the solution returns a double value greater than or equal to 0.0, and less than maxValue.

Download  Run Code

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