vendredi 8 novembre 2019

Random() creates the same random letters and numbers [duplicate]

This question already has an answer here:

I have a problem with a random function.

I am trying to create a string with 10 random letters/numbers.

However when I run the function, I get the same string 10 times in a row. What does that depend on and how can I truly create a random string in this case?

        void testfunction()
        {
            for (int i = 0; i < 10; i++)
            {
                String randomname = getRandomLetterNumbers(10);
                listBox1.Items.Add(randomname);
            }
        }
        public String getRandomLetterNumbers(int nrLetterNumbers)
        {
            String letters = "abcdefghijklmnopqrstuvwxyz0123456789";
            Random random = new Random(); String str = ""; int rand = 0;
            for (int i = 0; i < nrLetterNumbers; i++)
            {
                rand = random.Next(0, letters.Length);
                str = str + letters.Substring(rand, 1);
            }
            return str;
        }



Aucun commentaire:

Enregistrer un commentaire