Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random string generation - two generated one after another give same results

Tags:

string

c#

random

I have a simple piece of code:

public string GenerateRandomString()
        {
            string randomString = string.Empty;
            Random r = new Random();
            for (int i = 0; i < length; i++)
                randomString += chars[r.Next(chars.Length)];

            return randomString;
        }

If i call this function to generate two strings, one after another, they are identical... but if i debug through the two lines where the strings are generated - the results are different. does anyone know why is it happening?

like image 576
agnieszka Avatar asked Feb 03 '26 23:02

agnieszka


2 Answers

This is happening, because the calls happen very close to each other (during the same milli-second), then the Random constructor will seed the Random object with the same value (it uses date & time by default).

So, there are two solutions, actually.

1. Provide your own seed value, that would be unique each time you construct the Random object.

2. Always use the same Random object - only construct it once.

Personally, I would use the second approach. It can be done by making the Random object static, or making it a member of the class.

like image 123
Paulius Avatar answered Feb 05 '26 13:02

Paulius


The above answers are correct. I would suggest the following changes to your code though:

1) I would suggest using a StringBuilder instead of appending to the string all the time. Strings are immutable, so this is creating a new string each time you add to it. If you have never used StringBuilder, look it up. It is very useful for this sort of work.

2) You can make your method easier to reuse if you pass the length into the method itself. You could probably pass the chars array in as well, but I've left that out.

3) Use the same random object each time, as suggested above.

public string GenerateRandomString(int length)
{
    StringBuilder randomString = new StringBuilder(length);

    for (int i = 0; i < length; i++)
        randomString.Append(chars[(int)(_RandomObj.Next(chars.Length))].ToString());

     return randomString.ToString();
}
like image 42
Jamie Penney Avatar answered Feb 05 '26 12:02

Jamie Penney