CTS – Your Technology Partner

Don’t Take One From Max

Written by Craig Butler on December 6, 2012

By: William King

In .NET, the Random object’s “Next(int min, int max)” method returns a random number between the two provided values. It is critical to note that the min parameter is inclusive but the max parameter is exclusive.

This means that if you have an array of numbers like so:

int[] numbers = new int[] { 1, 2, 3, 4, 5 };

And want to randomly select an element from the array with a call to Random.Next like so:

r.Next(0, numbers.Length – 1);

You will never see the fifth element (numbers[4]) as a result.

We are all pretty conditioned to think in terms of zero-based indexed collections and always adjust the “total” value by subtracting one. Most likely, someone at MS (with the best of intentions) wanted to help prevent what they thought would be a pretty common error. The end result, however, is a bit unintuitive.

MSDN reference

Example code to verify:

Comments

comments