mercredi 27 avril 2016

C#: Why two different randomizers return same values? [duplicate]

This question already has an answer here:

I am trying to extend my programming skills in .NET as for the moment I just can code in PowerShell. Now I like to transfer a simple function to create a (low-security at all) password to C# but facing confusing situation.

I have two different solutions (I am not sure which one is better at all) in mind to do that see below: Version1

        public static char[] GetPassword(int length)
    {
        char[] password = new char[length];
        string passwordchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        Random randomtoken = new Random();
        for (int i = 0; i < length; i++)
        {
            password[i] = passwordchars[randomtoken.Next(passwordchars.Length)];
        }


        return password;
}

Version2

        public static string GetPassword2 (int length)
    {
        string password2 = "";
        string passwordchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        Random randomtoken2 = new Random();
        for (int i = 0; i < length; i++)
        {
            password2 += passwordchars[randomtoken2.Next(passwordchars.Length)];
        }

        return password2;

    }

Now I am calling the two versions from another class (importing the class with the password methods by "Using static" directive.

      static void Main()
    {
        char[] password = GetPassword(9);
        string password2 = GetPassword2(9);
        Console.WriteLine("1. Passwort:");
        Console.WriteLine(password);
        Console.WriteLine("2. Passwort:");
        Console.WriteLine(password2);
        return;
 }

Expected behaviour: As I am using two different methods with its own randomizer instance it should generate two completely different passwords (actually in my opinion even if I use the same randomizer)

Actual behaviour: Indeed the console output is twice exactly the same password. I have no explanation for this.

How is that? Can someone please explain me this? :) Thank you.




Aucun commentaire:

Enregistrer un commentaire