All entries for Thursday 19 September 2013

September 19, 2013

VB and C# functions generate the same 'random' strings each time

I'm using a standard pattern to generate random usercodes;

Function GenerateUsercode()
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)
sb.Append(s.Substring(idx, 1))
Return sb.ToString()
End Function

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)


uerpajfv uerpajfv

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.

September 2013

Mo Tu We Th Fr Sa Su
Aug |  Today  | Oct
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29

Search this blog



Blog archive

Not signed in
Sign in

Powered by BlogBuilder