Random
The Random
type returns a stream of numbers. It is best used as a field—this improves results when called from multiple methods.
It is important to understand the 2 arguments to random methods in VB.NET. The second value is exclusive—so it is never included in the results.
We create a Random
class
instance with its constructor. And with Next, we pass up to 2 arguments. Default values are used if we do not specify them as arguments.
Module Module1 Sub Main() Dim r As Random = New Random ' Get random numbers between 5 and 10. ' ... The values 5 through 9 are possible. Console.WriteLine(r.Next(5, 10)) Console.WriteLine(r.Next(5, 10)) Console.WriteLine(r.Next(5, 10)) End Sub End Module6 9 5
For modules or classes, it is best to store a Random
number generator as a field. The Random
instance will not repeat itself as much.
Module Module1 Sub Main() ' Write three random numbers. F() F() F() End Sub ''' <summary> ''' Write the next random number generated. ''' </summary> Private Sub F() ' Call Next method on the random object instance. Console.WriteLine(_r.Next) End Sub ''' <summary> ''' Store a random number generator. ''' </summary> Private _r As Random = New Random End Module1284029964 984949494 1322530626
Random
bytesSometimes we need to generate many random numbers at once. If we need bytes, we can generate random bytes with NextBytes
.
byte
individually could be used, but NextBytes
is clearer and simpler to read.Module Module1 Sub Main() Dim randomGenerator = New Random() ' Array of 10 random bytes. Dim buffer(9) As Byte ' Generate 10 random bytes. randomGenerator.NextBytes(buffer) For Each value In buffer Console.Write("[{0}]", value) Next End Sub End Module[250][186][58][0][205][149][152][237][30][26]
It is important to use the Random
type as a field in some situations, to reduce the possibility of repetition. Having fewer Random
number generators is also more efficient.