Random

Download vb.net eBook

Introduction

The Random class is used to generate non-negative pseudo-random integers that are not truly random, but are for general purposes close enough.

The sequence is calculated using an initial number (called the Seed) In earlier versions of .net, this seed number was the same every time an application was run. So what would happen was that you would get the same sequence of pseudo-random numbers every time the application was executed. Now, the seed is based on the time the object is declared.

Remarks

Finally, a note about randomization. As mentioned earlier, when you declare an instance of Random without any parameters, the constructor will use the current time as part of the calculation to create the initial seed number. Normally this is OK.

However. If you re-declare new instances over a very short space of time, each time the seed number is calculated, the time could be the same. Consider this code.

For i As Integer = 1 To 100000
    Dim rnd As New Random
    x = rnd.Next
Next

Because computers are very quick these days, this code will take a fraction of a second to run and on several dequential iterations of the loop, the system time will not have changed. So, the seed number will not change and the random number will be the same. If you want to generate lots of random numbers, declare the instance of random outside the loop in this simple example.

Dim rnd As New Random
For i As Integer = 1 To 100000
    x = rnd.Next
Next

The basic rule of thumb is don't re-instantiate random number generator over short periods of time.

Related Examples

Stats

12 Contributors: 1
Sunday, June 4, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook