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.
Next method. 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.
Argument 1 This is the minimum value returned by Next. It is inclusive, so can be a possible result.
Argument 2 This is the exclusive (not included) maximum. A max of 10 means the highest result possible is 9.
Dim r As Random = New Random
' Get random numbers between 5 and 10.' ... The values 5 through 9 are possible.
Field. 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.
Here The program writes three random numbers to the screen. The output will vary each time you run it.
' Write three random numbers.
''' Write the next random number generated.
Private Sub F()
' Call Next method on the random object instance.
''' Store a random number generator.
Private _r As Random = New Random
Random bytes. Sometimes we need to generate many random numbers at once. If we need bytes, we can generate random bytes with NextBytes.
Info A loop that generates each byte individually could be used, but NextBytes is clearer and simpler to read.
Dim randomGenerator = New Random()
' Array of 10 random bytes.
Dim buffer(9) As Byte
' Generate 10 random bytes.
For Each value In buffer
Review. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 10, 2023 (simplify).