Export (0) Print
Expand All

Random.Next Method (Int32, Int32)

Returns a random integer that is within a specified range.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

abstract Next : 
        minValue:int * 
        maxValue:int -> int  
override Next : 
        minValue:int * 
        maxValue:int -> int

Parameters

minValue
Type: System.Int32

The inclusive lower bound of the random number returned.

maxValue
Type: System.Int32

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

Return Value

Type: System.Int32
A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.

ExceptionCondition
ArgumentOutOfRangeException

minValue is greater than maxValue.

The Next(Int32, Int32) overload returns random integers that range from minValue to maxValue – 1. However, if maxValue equals minValue, the method returns minValue.

Unlike the other overloads of the Next method, which return only non-negative values, this method can return a negative random integer.

Notes to Inheritors

Starting with the .NET Framework version 2.0, if you derive a class from Random and override the Sample method, the distribution provided by the derived class implementation of the Sample method is not used in calls to the base class implementation of the Random.Next(Int32, Int32) method overload if the difference between the minValue and maxValue parameters is greater than Int32.MaxValue. Instead, the uniform distribution returned by the base Random class is used. This behavior improves the overall performance of the Random class. To modify this behavior to call the Sample method in the derived class, you must also override the Random.Next(Int32, Int32) method overload.

The following example uses the Random.Next(Int32, Int32) method to generate random integers with three distinct ranges. Note that the exact output from the example depends on the system-supplied seed value passed to the Random class constructor.

No code example is currently available or this language may not be supported.

The following example generates a random integer that it uses as an index to retrieve a string value from an array. Because the highest index of the array is one less than its length, the value of the Array.Length property is supplied as a the maxValue parameter.

No code example is currently available or this language may not be supported.

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Show:
© 2015 Microsoft