mpen
mpen

Reputation: 282955

Why can minValue == maxValue in Random.Next?

http://msdn.microsoft.com/en-us/library/2dx6wyd4.aspx

Apparently maxValue is an exclusive upper bound. So Random.Next(2,3) will always return 2. Random.Next(2,2) will also always return 2. Why do you suppose they even allow the min to be equal to the max in this case? It's misleading!

Upvotes: 2

Views: 345

Answers (2)

Will Vousden
Will Vousden

Reputation: 33368

It's just a convention, if somewhat misleading. You'd be able to construct such a scenario (where the output is the same every time) in any case. It's useful for selecting a random element of an array, for example:

var random = new Random();
var element = someArray[random.Next(0, someArray.Length)]; // Of course, the lower bound needn't be specified here.

Edit: Misunderstood your question! My guess is that it's either a) poor design or b) a convenience for when your two bounds will potentially be the same. I'd agree that it's unintuitive though.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1501133

Looks like just a bit of poor design to me. I agree that maxValue should be strictly greater than minValue - and it should throw an ArgumentOutOfRangeException if they're equal.

There are a few aspects to Random which I dislike - for one thing, it would be really nice to have it properly pluggable (in a well-documented way) so that you could have a subclass using a cryptographically secure source. It's possible now, but you basically need to know too much about the implementation, and which methods call which other ones :(

The gotchas around creating a new Random instance each time you go round a loop, and the obvious "fix" (a static variable) not being thread-safe are other annoyances.

Basically, I'm not terribly surprised to see another little wart :(

Upvotes: 5

Related Questions