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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.