Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Random.Next Method (Int32, Int32)

Returns a random number within a specified range.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
public virtual int Next(
	int minValue,
	int maxValue
)

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.

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

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.

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.