Generate a Random Number

Problem

You want to create a statistically random number quickly.

Solution

Create an instance of the System.Random class, and call the Next or NextDouble method.

Discussion

The Random class uses a pseudorandom number generator, which means that it uses an algorithm to generate numbers that are statistically random when viewed in sequence.

To use the Random class, you simply create an instance and call either Next or NextDouble. NextDouble returns a double-precision floating-point number greater than or equal to 0.0, and less than 1.0. Next generates an integer within the maximum and minimum range you specify.

Dim RandomGenerator As New Random() ' Retrieve a random fraction number from 0.0 to 1.0. Dim RandomDouble As Double = ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.