Random String Generator Returning Same String [duplicate]

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?

30 Answers
30

Leave a Comment