I was expecting (and thus using in places) the Random.Next Method (Int32, Int32) to return a random number between the lower and upper limits specified, both inclusive. However I was surprised to discover that actually "the range of return values includes minValue but not MaxValue."
As a result, doing something like this (in C#) will never return 5:
Random rand = new Random(); int num = rand.Next(1, 5);
Maybe this is obvious to some, but to me it wasn't and I was intuitively expecting both limits to be inclusive.
The logic behind having this behavior, I would guess, is the presumed familiarity of the C# developer with zero-based access. Since I found it confusing could it instead be a usability issue (we needed to run it by more developers to decide the correct behavior)?
Maybe MSDN documentation needs to start using bold red for words like "not" in such docs.
Confusingly, even though I was expecting the behaviour as described in the documentation (i.e., MaxValue should not be returned) in my application it occasionally does and raises an exception when causing an array to go out of bounds. Altering my parameters to avoid the exception slows execution down as MaxValue is returned so infrequently and implies a distribution problem with the Random class.
Anyone else seen this problem?
I propose the method description is renamed thus:
Random.Next(int minValue, int maxValueWhichCannotBeReturnedAsAResultOfNextButCannotBeExceeded)
Random.Next(int minValue, int beyondMaxValue)
would be easier?
Yup i got caught out by this too, after a bit of head scratching and good old Google i landed here, makes sense now though that it should be a half open interval.