-2

Sorry for my silly question. I am very new to learning c#. Right now i wanted to generate 5 random password for my assigment. After i finish my code, i notice that it generate 5 password but those 5 password are the same. i wanted those password to be different from one another.

Here is my code :

    static void Main(string[] args)
    {
        int length = 7;
        int i, n = 5;

        for (i = 0; i < n; i++)
        {
            string pass = CreateRandomPassword(length);
            Console.WriteLine("Password: " + pass);
        }

        Console.ReadLine();
    }

    private static string CreateRandomPassword(int length)
    {
        string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@$#?%&";
        Random random = new Random();

        char[] chars = new char[length];
        for (int i = 0; i < length; i++)
        {
            chars[i] = validChars[random.Next(0, validChars.Length)];
        }
        return new string(chars);
    }

    
}

}

The output it produce : Password: MBZAW09 Password: MBZAW09 Password: MBZAW09 Password: MBZAW09 Password: MBZAW09

i want the output to be like this : Password: MBZAW09 Password: edr$#c9 Password: 167&uj@ Password: @&dfy71 Password: 1gr6%8u

Can anyone help me out ???

New Here
  • 1
  • 1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 18 '21 at 20:13
  • Initialize the `Random` instance outside the `for` loop, not inside your `CreateRandomPassword()` method. – Progman Oct 18 '21 at 20:19
  • Use a version of .net that doesn't seed Random from the computer clock, if you're going to make new Randoma in a loop.. but even then.. – Caius Jard Oct 18 '21 at 20:34
  • i just finish the code. Thanks for the help :) @Progman – New Here Oct 18 '21 at 20:48
  • How about calling `Guid.NewGuid().ToString()`. There's (IIRC) 122 bits of strong entropy in the version 4 GUIDs it produces – Flydog57 Oct 18 '21 at 21:03

1 Answers1

0

From the Docs:

The Random() constructor uses the default seed value.

This means that the the seed for the Random object is created from the system clock time, which does NOT refresh in milliseconds, but by some larger amount.

Think of the Random object as a list of random numbers, generated based on the seed.

Because you're recreating the Random each call, and the program has a very short running time, you're regenerating the same list over and over again and restarting at the beginning of the list.

Solution: Create the Random in main, and pass it in as a method parameter. or, Make it an static variable, and create it once on start-up and keep reusing it.

Chris Cudmore
  • 29,793
  • 12
  • 57
  • 94