Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random string [duplicate]

Tags:

c#

.net

Possible Duplicate:
c# random string generator

I need to generate a random string with a given length. This is my code so far. The problem is the random string is like "RRRRRR" or "SSSSS" The same letter every time. Just when i restart the app the letter change. I need something like "asrDvgDgREGd"

    public string GenerateChar()
    {
        Random random = new Random();

        return Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))).ToString();
    }

    public string GenerateChar(int count)
    {        
        string randomString = "";

        for (int i = 0; i < count; i++)
        {
            nahodneZnaky += GenerateChar();
        }

        return randomString;
    }
like image 958
user137348 Avatar asked Oct 15 '09 14:10

user137348


1 Answers

Try using the same random object for the whole string, rather than initializing one for each char.

The random object will generate a "pseudo-random" number, based on mathematical progressions starting from a "seed" number. You can actually get the same sequence of "random" numbers if you initialize the Random object to the same seed every time.

Now, when you initialize Random without specifying a seed, it'll take the computer's clock as seed. In this case, you're probably doing it fast enough that the clock hasn't changed from one initialization to another, and you get always get the same seed.

You're better off initializing the Random object in your function that generates the random string, and passing it as a parameter to the GenerateChar function, so that you're calling NextDouble() several times on the same instance of the Random object, instead of only once on different instances of it.

like image 51
Daniel Magliola Avatar answered Sep 20 '22 06:09

Daniel Magliola