Mutiple random numbers in VB .Net
The .Net Random class works well on its own, if you just need one random number. By default it uses the system time for the seed value. Where problems occur is when you need multiple random numbers inside a loop.
When I called Random.Next within the loop, it would always return the same number, as the seed value was always the same, even using the millisecond property of Now().
My solution was to multiply the Random seed (milliseconds) by the loop value which resolved the issue.
Public Shared Function GetRandomNumber( _
ByVal iLowerBound As Integer, _
ByVal iUpperBound As Integer, _
Optional ByVal iSeedMultiplier As Integer = 1) As Integer
Dim Random As New Random(Now.Millisecond * iSeedMultiplier)
Return Random.Next(iLowerBound, iUpperBound + 1)
End Function
Example:
For i = 1 To 5
strKey = i.ToString & "|" & GetRandomNumber(1, 10, i).ToString
Next
- Download this code: GetRandomNumber.txt