Random Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet certain statistical requirements for randomness.

Inheritance Hierarchy

System.Object
  System.Random

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

Syntax

'Declaration
<ComVisibleAttribute(True)> _
Public Class Random
[ComVisibleAttribute(true)]
public class Random

The Random type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Random() Initializes a new instance of the Random class, using a time-dependent default seed value.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Random(Int32) Initializes a new instance of the Random class, using the specified seed value.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Next() Returns a nonnegative random number.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Next(Int32) Returns a nonnegative random number less than the specified maximum.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Next(Int32, Int32) Returns a random number within a specified range.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 NextBytes Fills the elements of a specified array of bytes with random numbers.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 NextDouble Returns a random number between 0.0 and 1.0.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Sample Returns a random number between 0.0 and 1.0.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Remarks

Pseudo-random numbers are chosen with equal probability from a finite set of numbers. The chosen numbers are not completely random because a definite mathematical algorithm is used to select them, but they are sufficiently random for practical purposes. The current implementation of the Random class is based on Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth. "The Art of Computer Programming, volume 2: Seminumerical Algorithms". Addison-Wesley, Reading, MA, second edition, 1981.

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers. The following example illustrates that two Random objects that are instantiated in close sucession generate an identical series of random numbers.

Dim bytes1(99), bytes2(99) As Byte
Dim rnd1 As New Random()
Dim rnd2 As New Random()

rnd1.NextBytes(bytes1)
rnd2.NextBytes(bytes2)

outputBlock.Text += "First Series:" & vbCrLf
For ctr As Integer = bytes1.GetLowerBound(0) To bytes1.GetUpperBound(0)
   outputBlock.Text += String.Format("{0, 5}", bytes1(ctr))
   If (ctr + 1) Mod 10 = 0 Then outputBlock.Text &=  vbCrLf
Next
outputBlock.Text += vbCrLf
outputBlock.Text += "Second Series:" & vbCrLf
For ctr As Integer = bytes2.GetLowerBound(0) To bytes2.GetUpperBound(0)
   outputBlock.Text += String.Format("{0, 5}", bytes2(ctr))
   If (ctr + 1) Mod 10 = 0 Then outputBlock.Text &=  vbCrLf
Next
' The example displays the following output:
'       First Series:
'          97  129  149   54   22  208  120  105   68  177
'         113  214   30  172   74  218  116  230   89   18
'          12  112  130  105  116  180  190  200  187  120
'           7  198  233  158   58   51   50  170   98   23
'          21    1  113   74  146  245   34  255   96   24
'         232  255   23    9  167  240  255   44  194   98
'          18  175  173  204  169  171  236  127  114   23
'         167  202  132   65  253   11  254   56  214  127
'         145  191  104  163  143    7  174  224  247   73
'          52    6  231  255    5  101   83  165  160  231
'       
'       Second Series:
'          97  129  149   54   22  208  120  105   68  177
'         113  214   30  172   74  218  116  230   89   18
'          12  112  130  105  116  180  190  200  187  120
'           7  198  233  158   58   51   50  170   98   23
'          21    1  113   74  146  245   34  255   96   24
'         232  255   23    9  167  240  255   44  194   98
'          18  175  173  204  169  171  236  127  114   23
'         167  202  132   65  253   11  254   56  214  127
'         145  191  104  163  143    7  174  224  247   73
'          52    6  231  255    5  101   83  165  160  231      
byte[] bytes1 = new byte[100];
byte[] bytes2 = new byte[100];
Random rnd1 = new Random();
Random rnd2 = new Random();

rnd1.NextBytes(bytes1);
rnd2.NextBytes(bytes2);

outputBlock.Text += "First Series:" + "\n";
for (int ctr = bytes1.GetLowerBound(0);
     ctr <= bytes1.GetUpperBound(0);
     ctr++)
{
   outputBlock.Text += String.Format("{0, 5}", bytes1[ctr]);
   if ((ctr + 1) % 10 == 0) outputBlock.Text +=  "\n";
}
outputBlock.Text +=  "\n";
outputBlock.Text += "Second Series:" + "\n";
for (int ctr = bytes2.GetLowerBound(0);
     ctr <= bytes2.GetUpperBound(0);
     ctr++)
{
   outputBlock.Text += String.Format("{0, 5}", bytes2[ctr]);
   if ((ctr + 1) % 10 == 0) outputBlock.Text +=  "\n";
}
// The example displays the following output:
//       First Series:
//          97  129  149   54   22  208  120  105   68  177
//         113  214   30  172   74  218  116  230   89   18
//          12  112  130  105  116  180  190  200  187  120
//           7  198  233  158   58   51   50  170   98   23
//          21    1  113   74  146  245   34  255   96   24
//         232  255   23    9  167  240  255   44  194   98
//          18  175  173  204  169  171  236  127  114   23
//         167  202  132   65  253   11  254   56  214  127
//         145  191  104  163  143    7  174  224  247   73
//          52    6  231  255    5  101   83  165  160  231
//       
//       Second Series:
//          97  129  149   54   22  208  120  105   68  177
//         113  214   30  172   74  218  116  230   89   18
//          12  112  130  105  116  180  190  200  187  120
//           7  198  233  158   58   51   50  170   98   23
//          21    1  113   74  146  245   34  255   96   24
//         232  255   23    9  167  240  255   44  194   98
//          18  175  173  204  169  171  236  127  114   23
//         167  202  132   65  253   11  254   56  214  127
//         145  191  104  163  143    7  174  224  247   73
//          52    6  231  255    5  101   83  165  160  231        

This problem can be avoided by creating a single Random object rather than multiple ones.

To improve performance, create one Random object to generate many random numbers over time, instead of repeatedly creating new Random objects to generate one random number.

To generate a cryptographically secure random number suitable for creating a random password, for example, use a class derived from System.Security.Cryptography.RandomNumberGenerator such as System.Security.Cryptography.RNGCryptoServiceProvider.

Notes to Callers

The implementation of the random number generator in the Random class is not guaranteed to remain the same across major versions of the .NET Framework for Silverlight. As a result, your application code should not assume that the same seed will result in the same pseudo-random sequence in different versions of the .NET Framework for Silverlight.

Notes to Inheritors

The Random.Next(), Random.Next(Int32, Int32), and NextBytes methods do not necessarily call the derived class implementation of the Sample method. As a result, classes derived from Random should override all three of these methods.

Examples

The following example creates a single random number generator and calls its NextBytes, Next, and NextDouble methods to generate sequences of random numbers within different ranges.

' Instantiate random number generator using system-supplied value as seed.
Dim rand As New Random()
' Generate and display 5 random byte (integer) values.
Dim bytes(4) As Byte
rand.NextBytes(bytes)
outputBlock.Text += "Five random byte values:" & vbCrLf
For Each byteValue As Byte In bytes
   outputBlock.Text += String.Format("{0, 5}", byteValue)
Next
outputBlock.Text += vbCrLf
' Generate and display 5 random integers.
outputBlock.Text += "Five random integer values:" & vbCrLf
For ctr As Integer = 0 To 4
   outputBlock.Text += String.Format("{0,15:N0}", rand.Next)
Next
outputBlock.Text += vbCrLf
' Generate and display 5 random integers between 0 and 100.'
outputBlock.Text += "Five random integers between 0 and 100:" & vbCrLf
For ctr As Integer = 0 To 4
   outputBlock.Text += String.Format("{0,8:N0}", rand.Next(101))
Next
outputBlock.Text += vbCrLf
' Generate and display 5 random integers from 50 to 100.
outputBlock.Text += "Five random integers between 50 and 100:" & vbCrLf
For ctr As Integer = 0 To 4
   outputBlock.Text += String.Format("{0,8:N0}", rand.Next(50, 101))
Next
outputBlock.Text += vbCrLf
' Generate and display 5 random floating point values from 0 to 1.
outputBlock.Text += "Five Doubles." & vbCrLf
For ctr As Integer = 0 To 4
   outputBlock.Text += String.Format("{0,8:N3}", rand.NextDouble())
Next
outputBlock.Text += vbCrLf
' Generate and display 5 random floating point values from 0 to 5.
outputBlock.Text += "Five Doubles between 0 and 5." & vbCrLf
For ctr As Integer = 0 To 4
   outputBlock.Text += String.Format("{0,8:N3}", rand.NextDouble() * 5)
Next
' Sample console output might appear as follows:
'    Five random byte values:
'      194  185  239   54  116
'    Five random integer values:
'        507,353,531  1,509,532,693  2,125,074,958  1,409,512,757    652,767,128
'    Five random integers between 0 and 100:
'          16      78      94      79      52
'    Five random integers between 50 and 100:
'          56      66      96      60      65
'    Five Doubles.
'       0.943   0.108   0.744   0.563   0.415
'    Five Doubles between 0 and 5.
'       2.934   3.130   0.292   1.432   4.369      
// Instantiate random number generator using system-supplied value as seed.
Random rand = new Random();
// Generate and display 5 random byte (integer) values.
byte[] bytes = new byte[4];
rand.NextBytes(bytes);
outputBlock.Text += "Five random byte values:" + "\n";
foreach (byte byteValue in bytes)
   outputBlock.Text += String.Format("{0, 5}", byteValue);
outputBlock.Text +=  "\n";
// Generate and display 5 random integers.
outputBlock.Text += "Five random integer values:" + "\n";
for (int ctr = 0; ctr <= 4; ctr++)
   outputBlock.Text += String.Format("{0,15:N0}", rand.Next());
outputBlock.Text +=  "\n";
// Generate and display 5 random integers between 0 and 100.//
outputBlock.Text += "Five random integers between 0 and 100:" + "\n";
for (int ctr = 0; ctr <= 4; ctr++)
   outputBlock.Text += String.Format("{0,8:N0}", rand.Next(101));
outputBlock.Text +=  "\n";
// Generate and display 5 random integers from 50 to 100.
outputBlock.Text += "Five random integers between 50 and 100:" + "\n";
for (int ctr = 0; ctr <= 4; ctr++)
   outputBlock.Text += String.Format("{0,8:N0}", rand.Next(50, 101));
outputBlock.Text +=  "\n";
// Generate and display 5 random floating point values from 0 to 1.
outputBlock.Text += "Five Doubles." + "\n";
for (int ctr = 0; ctr <= 4; ctr++)
   outputBlock.Text += String.Format("{0,8:N3}", rand.NextDouble());
outputBlock.Text +=  "\n";
// Generate and display 5 random floating point values from 0 to 5.
outputBlock.Text += "Five Doubles between 0 and 5." + "\n";
for (int ctr = 0; ctr <= 4; ctr++)
   outputBlock.Text += String.Format("{0,8:N3}", rand.NextDouble() * 5);
// Sample console output might appear as follows:
//    Five random byte values:
//      194  185  239   54  116
//    Five random integer values:
//        507,353,531  1,509,532,693  2,125,074,958  1,409,512,757    652,767,128
//    Five random integers between 0 and 100:
//          16      78      94      79      52
//    Five random integers between 50 and 100:
//          56      66      96      60      65
//    Five Doubles.
//       0.943   0.108   0.744   0.563   0.415
//    Five Doubles between 0 and 5.
//       2.934   3.130   0.292   1.432   4.369      

Version Information

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

Platforms

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

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference