Export (0) Print
Expand All

Random Class

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

To browse the .NET Framework source code for this type, see the Reference Source.

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

[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class Random

The Random type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsRandom()Initializes a new instance of the Random class, using a time-dependent default seed value.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsRandom(Int32)Initializes a new instance of the Random class, using the specified seed value.
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsNext()Returns a nonnegative random integer.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsNext(Int32)Returns a nonnegative random integer that is less than the specified maximum.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsNext(Int32, Int32)Returns a random integer that is within a specified range.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsNextBytesFills the elements of a specified array of bytes with random numbers.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsNextDoubleReturns a random floating-point number between 0.0 and 1.0.
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsSampleReturns a random floating-point number between 0.0 and 1.0.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Top

NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

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 succession generate an identical series of random numbers.

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

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 a 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.

The Random class and thread safety

Instead of instantiating individual Random objects, we recommend that you create a single Random instance to generate all the random numbers needed by your app. However, Random objects are not thread safe. If your app calls Random methods from multiple threads, you must use a synchronization object to ensure that only one thread can access the random number generator at a time. If you don't ensure that the Random object is accessed in a thread-safe way, calls to methods that return random numbers return 0.

The following example uses the C# lock Statement and the Visual Basic SyncLock statement to ensure that a single random number generator is accessed by 11 threads in a thread-safe manner. Each thread generates two million random numbers, counts the number of random numbers generated and calculates their sum, and then updates the totals for all threads when it finishes executing.

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

The example ensures thread-safety in the following ways:

  • The ThreadStaticAttribute attribute is used to define thread-local variables for the total of random numbers generated and their sum for each thread.

  • A lock protects access to the variables for the total count and sum of all random numbers generated on all threads.

  • A semaphore (the CountdownEvent object) is used to ensure that the main thread blocks until all other threads complete execution.

  • The example checks whether the random number generator has become corrupted by determining whether two consecutive calls to random number generation methods return 0. If corruption is detected, the example uses the CancellationTokenSource object to signal that all threads should be canceled.

  • Before generating each random number, each thread checks the state of the CancellationToken object. If cancellation is requested, the example calls the CancellationToken::ThrowIfCancellationRequested method to cancel the thread.

The following example is identical to the first, except that it uses a Task object and a lambda expression instead of Thread objects.

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

It differs from the first example in the following ways:

  • Because the variables to keep track of the number of random numbers generated and their sum in each task are local to the task, there is no need to use the ThreadStaticAttribute attribute.

  • The static Task::WaitAll method is used to ensure that the main thread doesn't complete before all tasks have finished. There is no need for the CountdownEvent object.

  • The exception that results from task cancellation is surfaced in the Task::WaitAll method. In the previous example, it is handled by each thread.

Notes to Callers

The implementation of the random number generator in the Random class isn't guaranteed to remain the same across major versions of the .NET Framework. As a result, you shouldn't assume that the same seed will result in the same pseudo-random sequence in different versions of the .NET Framework.

Notes to Inheritors

In the .NET Framework versions 1.0 and 1.1, a minimum implementation of a class derived from Random required overriding the Sample method to define a new or modified algorithm for generating random numbers. The derived class could then rely on the base class implementation of the Random::Next(), Random::Next(Int32), Random::Next(Int32, Int32), NextBytes, and NextDouble methods to call the derived class implementation of the Sample method.

In the .NET Framework version 2.0 and later, the behavior of the Random::Next(), Random::Next(Int32, Int32), and NextBytes methods have changed so that these methods do not necessarily call the derived class implementation of the Sample method. As a result, classes derived from Random that target the .NET Framework 2.0 and later should also override these three methods.

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.

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.

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

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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