All entries for Thursday 19 September 2013
September 19, 2013
I'm using a standard VB.net pattern to generate random usercodes;
Dim s As String = "abcdefghijklmnopqrstuvwxyz"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, s.Length)
However, if I call it twice, quickly, it generates the same 'random' usercode. Here's what it looks like when I call it with:
dim pass1 as string = GenerateUsercode()
dim pass2 as string = GenerateUsercode()
System.Diagnostics.Debug.Write(pass1 & " " & pass2)
It looks like something is being cached. If I set a breakpoint and step throgh the code, it generates two random strings. I tried resetting things; reDIMming all the variables after they'd been used, resetting the stringbuilder to zero length, and started Googling in earnest. This blog had the answer; The problem is that the 'Dim r As New Random' line in the function is being executed so quickly (presumably a combination of fast processor, very good compliler optimisation) that the random seed is being created with the same value each time it's generated.
There's actually no need to regenerate the seed every time because the
gets the next random number based on the seed. The solution is to move the 'Dim r As New Random' out of the function to the main delarations area where it executes once, and the pattern works perfectly.