How to Generate Random Numbers in .NET

  • google plus

In Brief...

The steps below describe how to generate random numbers in .NET.

Instructions

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.

  1. 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.
    C#
    
    	//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);
    	

    VB.Net
    
    	'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)
    	

  2. Next we declare some variables to hold the results of the various method calls.
    C#
    //declare variables to hold the result
    	int resultInt;
    	double resultDouble;
    	byte[] resultBytes = new byte[12];

    VB.Net
    'declare variables to hold the result
    	Dim resultInt As Integer
    	Dim resultDouble As Double
    	Dim resultBytes(12) As Byte
  3. Finally, we exercise each of the methods and retrieve the results
    C#
    //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);

    VB.Net
    
    	'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)
  4. 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.

Author: Michael Osborne

Discuss