Random Numbers in .NET April 20 2006
To generate random numbers in .NET is fairly straight forward however there is one pitfall that you must avoid in order to get the numbers not bound to the clock!
DO NOT INSTANTIATE THE NUMBER GENERATOR EVERYTIME YOU GENERATE NUMBERS
In other words, if you have a method that you are calling to generate the random numbers in a library, do not create an instance everytime you are looking to generate random numbers.
Eg.
RandomLibrary.vb
public class myRandomLibrary
public function getRandNumber() as integer
Dim myRandObject as new Random
return(myRandObject.Next(1, 100))
end function
end class
This is not going to work because you are calling new() on the random number generator everytime you use it.
Instread, try initializing the random number generator within the class block AND creating a global instance of this library within the actual class you are generating the random numbers in.
Here is a class using some borrowed code from DeveloperFusion
Public Class clsMathRandom
Private objRandom As New System.Random(CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue, Integer))
Public Function RandString(ByVal intMaxLength As Integer) As String
Dim myStr(intMaxLength) As Char
Dim i As Integer
For i = 0 To intMaxLength
myStr(i) = Chr(GetRandomNumber(65, 90))
Next
Return (myStr)
End Function
Public Function GetRandomNumber( _
Optional ByVal Low As Integer = 1, _
Optional ByVal High As Integer = 100) As Integer
‘ Returns a random number,
‘ between the optional Low and High parameters
Return objRandom.Next(Low, High + 1)
End Function
End Class
And now to use it within another class
Private __myRandObj As clsMathRandom
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
initRand()
End Sub
Private Sub initRand()
Me.__myRandObj = New clsMathRandom
End Sub
Private Function RandInt(ByVal intMin As Integer, ByVal intMax As Integer) As Integer
Return (Me.__myRandObj.GetRandomNumber(intMin, intMax))
End Function
Private Function RandString() As String
Return (Me.__myRandObj.RandString(100))
End Function
From here on in, only use the local references. If you re-instantiate the number generator the seed will get reset!
Ref : http://www.developerfusion.co.uk/show/3940/
- Posted in : General
- Author : site admin

Comments»
no comments yet - be the first?