I've developed a random string generator but it's not behaving quite as I'm hoping. My goal is to be able to run this twice and generate two distinct four character random strings. However, it just generates one four character random string twice.
Here's the code and an example of its output:
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
// get 1st random string
string Rand1 = RandomString(4);
// get 2nd random string
string Rand2 = RandomString(4);
// create full rand string
string docNum = Rand1 + "-" + Rand2;
...and the output looks like this: UNTE-UNTE ...but it should look something like this UNTE-FWNU
How can I ensure two distinctly random strings?
You're instantiating the
Random
object inside your method.The
Random
object is seeded from the system clock, which means that if you call your method several times in quick succession it'll use the same seed each time, which means that it'll generate the same sequence of random numbers, which means that you'll get the same string.To solve the problem, move your
Random
instance outside of the method itself (and while you're at it you could get rid of that crazy sequence of calls toConvert
andFloor
andNextDouble
):You should have one class-level Random object initiated once in the constructor and reused on each call (this continues the same sequence of pseudo-random numbers). The parameterless constructor already seeds the generator with Environment.TickCount internally.
You're making the Random instance in the method, which causes it to return the same values when called in quick succession. I would do something like this:
(modified version of your code)
A LINQ one-liner for good measure (assuming a
private static Random Random
)...//A very Simple implementation
//Now just call RandomStr() Method
I created this method.
It works great.