Jonathan Gilbert
Jonathan Gilbert

Reputation: 3840

Can Random.Next() ever return int.MaxValue?

The documentation for the Random.Next() method states that it returns:

A 32-bit signed integer that is greater than or equal to 0 and less than MaxValue.

But, I took a peek at the implementation, and while I don't understand the algorithm (a quick Google search suggests that it is a subtractive generator), I can't see any way in which a value of exactly int.MaxValue is ruled out.

If, for pedantic reasons, someone wants a random number across the entire range of 32-bit integers, does Random.Next() alone suffice, or does it become necessary to do something like assemble two separate 16-bit samples?

Upvotes: 2

Views: 440

Answers (1)

Tigerware
Tigerware

Reputation: 3904

It will always be less than int.MaxValue.

In your linked source code it explicitly handles int.MaxValue:

if (retVal == MBIG) retVal--;

MBIG is defined earlier:

private const int MBIG = int.MaxValue;

https://github.com/dotnet/runtime/blob/master/src/libraries/System.Private.CoreLib/src/System/Random.cs#L105

Upvotes: 4

Related Questions