Random numbers may be generated in the Microsoft .NET Framework by
using the Random class. This class is instantiated using the following VB.NET
code:
'Create a new Random class in VB.NET
Dim RandomClass As New Random()
This class can subsequently be used to generate random numbers in a number of different
data types.
Generating random integers
Once the Random class has been instantiated, a random integer can be obtained by
calling the Next method of the Random class:
Dim RandomNumber As Integer
RandomNumber = RandomClass.Next()
Using this code sample, the value of the RandomNumber variable will be
assigned a random whole number between 1 and 2,147,483,647.
In most programming situations, it is useful to be able to create a random number
within a certain size range. In this case, the Next method should be invoked with
a different constructor - one that takes two arguments: the minimum value and the
maximum value for the random number. For example, the following assigns a value
to RandomNumber that is greater or equal to 40 and less than 400:
Dim RandomNumber As Integer
RandomNumber = RandomClass.Next(40, 400)
Remember that an ArgumentOutOfRangeException will be raised if the minimum
value is larger than the maximum value specified.
It is also possible to use a further constructor to specify just the maximum value of
the random integer. The following will return a return a random integer that is greater or
equal to 0 and less than 800:
Dim RandomNumber As Integer
RandomNumber = RandomClass.Next(800)
As with the previous code sample, an ArgumentOutOfRangeException exception
will be raised if the maximum value is smaller than 0.
Generating random floating point numbers
As well as returning random integers, the Random class can also return floating point
numbers. The NextDouble method returns a random number as a Double data
type. The random number's value is always greater or equal to 0.0, and less
than 1.0:
Dim RandomNumber As Double
RandomNumber = RandomClass.NextDouble()
Generating a random byte array
Finally, the Random class can also be used to populate a byte array with random bytes.
This is achieved by calling the NextBytes method of the Random class object.
Dim ByteArray(64) as Byte
Random.NextBytes(ByteArray)
The array is then populated with bytes of values between 0 and 255.
Note that these random bytes will not be sufficiently random for use in cryptography.
|