How to Generate Random Numbers in .NET
The steps below describe how to generate random numbers in .NET.
To generate random numbers in a .Net application, we use the framework class "Random". Random is in the mscorlib library so there is no need to bring any additional namespaces into scope. The "Random" class provides five methods used to generate various types of random number.
- To begin, we Instantiate the Random Class. The class has two constructor overloads. One is the default constructor (receives no parameters) which uses a time-dependent default seed value to initialize the class. The second constructor receives an Int32 seed value which is used to initialize the class.
//Create an instance of the Random class //Using the Default Constructor Random r = new Random(); //Or Passing in a seed value Random r2 = new Random(65);
'Create an instance of the Random class 'Using the Default Constructor Dim r As New Random() 'Or Passing in a seed value Dim r2 As New Random(65)
- Next we declare some variables to hold the results of the various method calls.
//declare variables to hold the result int resultInt; double resultDouble; byte resultBytes = new byte;
'declare variables to hold the result Dim resultInt As Integer Dim resultDouble As Double Dim resultBytes(12) As Byte
Finally, we exercise each of the methods and retrieve the results
//return a nonnegative random integer resultInt = r.Next(); //return a random integer between 50 and 100 resultInt = r.Next(50, 100); //return a nonnegative integer that is less than 2000 resultInt = r.Next(2000); //return a random floating point integer betweem 0.00 and 1.00 resultDouble= r.NextDouble(); //Fill the array with random numbers r.NextBytes(resultBytes);
'return a nonnegative random integer resultInt = r.Next() 'return a random integer between 50 and 100 resultInt = r.Next(50, 100) 'return a nonnegative integer that is less than 2000 resultInt = r.Next(2000) 'return a random floating point integer betweem 0.00 and 1.00 resultDouble = r.NextDouble() 'Fill the array with random numbers r.NextBytes(resultBytes)
- Be aware the Random class is a "psuedo random number generator". In other words, it is not truly random. The "randomness" does, however, meet certain statistical requirements for random numbers.