Is the Random.Next code incorrect?

I installed a plugin (extensions for contract code editors from Microsoft) that displays all the code contracts for .NET.

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

+4
source share
2 answers

This is not exclusive, and MSDN does not state that it is. Well, well, he uses the word β€œexclusive” when it comes to maxValue , which is less clear, but the reality is that in the vast majority of cases it really is exclusive, as expected.

However, there are some angular cases: to be specific with examples, Next(0) returns 0 ; Next(4,4) returns 4 . It is enabled if it does not have an option, and this is described in the "Return Value" section on MSDN:

For a quote from Next(maxValue) :

However, if maxValue is zero, maxValue is returned.

and Next(minValue,maxValue) :

If minValue is equal to maxValue, minValue is returned.

(which, of course, could be said: " maxValue returned")

In both cases, a return of maxValue .

The one exception is the parameter without Next() parameters, which is documented as strictly < int.MaxValue .

+6
source

Since the MSDN contract is more stringent than the contract concluded with code contracts, the contract used by code contracts is clearly correct, but possibly not tight.

On the other hand, if you were to put the custom implementation of Next in your own derived class Random , this might not match the contract specified in MSDN, but the contract check did not notice an error. Therefore, it is still recommended for MS to remove the mismatch between the two versions of the contract.

I would not be surprised if it was originally an MSDN error, and they changed the code to fit the specification.

I suggest you send an MS Connect message asking you to improve one of them.

MSDN Quote for Next()

A 32-bit signed integer greater than or equal to zero and less than MaxValue.

+2
source

All Articles