Search code examples
.netrandomcode-contracts

Is the Random.Next code contract incorrect?


I've installed a plugin (Code Contract Editor Extensions by Microsoft) which displays all code contracts for .NET.

When I look at the contract for Random.Next it says ensures result <= maxValue while MSDN states that maxValue is exclusive. Shouldn't the contract say ensures result < maxValue?


Solution

  • It is not exclusive, and MSDN does not state that it is. Well, OK, it does use the word "exclusive" when talking about maxValue, which is less than clear, but the reality is that in the vast majority of cases it is indeed exclusive as expected.

    There are, however, some corner-cases: to be specific with examples, Next(0) returns 0; Next(4,4) returns 4. It is inclusive when it has no option, and this is documented in the "Return Value" sections on MSDN:

    To quote from Next(maxValue):

    However, if maxValue equals zero, maxValue is returned.

    and from Next(minValue,maxValue):

    If minValue equals maxValue, minValue is returned.

    (which of course could also be stated "maxValue is returned")

    So in both cases, it is possible for maxValue to be returned.

    The only exception is the parameterless Next() which is documented as being strictly < int.MaxValue.