debugging - My static C# function is playing games with me... totaly weird! -
so, i've written small and, thought, easy method in c#. static method meant used simple password suggestion generator, , code looks this:
public static string createrandompassword(int outputlength, string source = "") { var output = string.empty; (var = 0; < outputlength; i++) { var randomobj = new random(); output += source.substring(randomobj.next(source.length), 1); } return output; }
i call function this:
var randompassword = stringhelper.createrandompassword(5, "abcdefghijklmnopqrstuvwxyz1234567890");
now, method return random strings "aaaaaa", "bbbbbb", "888888" etc.. , thought should return strings "a8jk2a", "82mok7" etc.
however, , here wierd part; if place breakpoint, , step through iteration line line, correct type of password in return. in 100% of other cases, when im not debugging, gives me crap "aaaaaa", "666666", etc..
how possible? suggestion appreciated! :-)
btw, system: visual studio 2010, c# 4.0, asp.net mvc 3 rtm project w/ asp.net development server. haven't tested code in other environments.
move declaration randomobj outside loop. when you're debugging it, creates new seed each time, because there's enough time difference seed different. when you're not debugging, seed time same each iteration of loop, it's giving same start value each time.
and minor nit -- it's habit use stringbuilder rather string sort of thing, don't have re-initialize memory space every time append character string.
in other words, this:
public static string createrandompassword(int outputlength, string source = "") { var output = new stringbuilder(); var randomobj = new random(); (var = 0; < outputlength; i++) { output.append(source.substring(randomobj.next(source.length), 1)); } return output.tostring(); }
Comments
Post a Comment