Random Constructor (Int32)

 

Initializes a new instance of the Random class, using the specified seed value.

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

new : 
        Seed:int -> Random

Parameters

Seed
Type: System.Int32

A number used to calculate a starting value for the pseudo-random number sequence. If a negative number is specified, the absolute value of the number is used.

Providing an identical seed value to different Random objects causes each instance to produce identical sequences of random numbers. This is often done when testing apps that rely on random number generators.

If your application requires different random number sequences, invoke this constructor repeatedly with different seed values. One way to produce a unique seed value is to make it time-dependent. For example, derive the seed value from the system clock, as the Random() overload does. However, the system clock might not have sufficient resolution to provide different invocations of this constructor with a different seed value. This results in random number generators that generate identical sequences of pseudo-random numbers, as illustrated by the first two Random objects in the following example. To prevent this, apply an algorithm to differentiate the seed value in each invocation, or call the Thread.Sleep method to ensure that you provide each constructor with a different seed value.

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

Another option is to instantiate a single Random object that you use to generate all the random numbers in your application. This yields slightly better performance, since instantiating a random number generator is fairly expensive.

The following example creates Random objects with the class constructor that takes a seed parameter and generates a sequence of random integers and doubles. The example illustrates that the same sequence is generated when the Random object is created again with the constructor and seed parameter.

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

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
Show: