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.
//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)
//declare variables to hold the result
int resultInt;
double resultDouble;
byte[] resultBytes = new byte[12];
'declare variables to hold the result
Dim resultInt As Integer
Dim resultDouble As Double
Dim resultBytes(12) As Byte
//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)
Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.