C# Random.Next - never returns the upper bound?
Solution 1:
The maxValue
for the upper-bound in the Next()
method is exclusive—the range includes minValue
, maxValue-1
, and all numbers in between.
Solution 2:
The documentation says the upper bound is exclusive. Exclusive means that it is not included in the possible return set. In a more mathematical notation 0 <= x < 5
in this case.
Solution 3:
Straight from the documentation:
Summary:
Returns a random number within a specified range.
Parameters:
minValue:
The inclusive lower bound of the random number returned.
maxValue:
The exclusive upper bound of the random number returned. maxValue must be
greater than or equal to minValue.
Returns:
A 32-bit signed integer greater than or equal to minValue and less than maxValue;
that is, the range of return values includes minValue but not maxValue. If
minValue equals maxValue, minValue is returned.
If you look at the parameters, you will see that minValue
is inclusive (which is why your 0 occurs) and maxValue
is exclusive (your 5 never occurs).
Solution 4:
Good way to remember it is to consider max as amount of numbers from which it takes random number.
So random.Next(0,2)
means that it takes random out of 2 numbers starting from 0: 0 and 1.
Solution 5:
This has been written a long time ago but I will comment anyway. I think the main reason for that design decision is that most if not all random number generator at their core generate numbers from 0 to 2^32-1. So if you specify Int32.MaxValue you will never get that number. Having an exception for one number must have been not acceptable to the designers so they decided to have the bracket exclusive. Problem solved!