C# Random.Next(int, int) – how to define the bounds correctly

The devil is in the detail. Recently I wanted to create random numbers between 0 and 1 in C#. The Visual Studio tells us that we have to use Random.Next (int, int) method, whereby the first integer defines the lower limit and the second integer defines the upper limit. No more and no less. So based on Visual Studio’s description the following function should work:

Random rnd = new Random();
int random = rnd.Next(0,1);

Wrong! So you’ll get only one thing – in fact zeros. So I had to dip into the MSDN library to find a solution. There is explained, on the contrary to IntelliSense from Visual Studio, that the lower bound is inclusive and the upper bound is exclusive.


Type: System.Int32
The inclusive lower bound of the random number returned.

Type: System.Int32
The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.

In plain language this means, to reach my aim and generate zeros and ones, the function call should look as follows:

Random rnd = new Random();
int random = rnd.Next(0,2);

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked