Reputation:
I'm not sure it's an issue, but something looks like not correct in the message.
My first try:
try
{
var r = new Random();
Console.WriteLine(r.Next(-1));
}
catch (Exception e)
{
Console.WriteLine(e.GetType().ToString());
Console.WriteLine(e.Message);
}
Output:
System.ArgumentOutOfRangeException
'maxValue' must be greater than zero.
Parameter name: maxValue
My second try:
try
{
var r = new Random();
Console.WriteLine(r.Next(0));
}
catch (Exception e)
{
Console.WriteLine(e.GetType().ToString());
Console.WriteLine(e.Message);
}
Output:
0
So, the problem is: why is 0
greater than zero?
Upvotes: 2
Views: 3829
Reputation: 446
The value cant be negative.zero or above is acceptable.That's why your are getting above answer.
Upvotes: 0
Reputation: 5141
By definition from MSDN Random.Next Method (Int32).
maxValue Type: System.Int32 The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.
So yes we can say that the error message is misleading. It should be greater than or equal to zero.
Upvotes: 1
Reputation: 2885
Parameters
maxValue
Type: System.Int32
The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.
From Random.Next Method (Int32)
Upvotes: 0
Reputation: 247058
maxValue: The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.
Upvotes: 0
Reputation: 45101
If you take a look at the source code:
/*=====================================Next=====================================
**Returns: An int [0..maxValue)
**Arguments: maxValue -- One more than the greatest legal return value.
**Exceptions: None.
==============================================================================*/
public virtual int Next(int maxValue) {
if (maxValue<0) {
throw new ArgumentOutOfRangeException("maxValue", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "maxValue"));
}
Contract.EndContractBlock();
return (int)(Sample()*maxValue);
}
The value must be positive and zero is positive.
Upvotes: 1