C # Passing one variable to two "out" parameters

Is it normal that "user1" and "user2" point to the same link in the example below?

I know that I pass one variable 'notUsed' for both parameters, but it has not been set yet, so it does not contain a link to anything. I was very shocked to see that user1 and user2 are connected to each other.

static void CheckPasswords(out string user1, out string user2)
{
    user1 = "A";
    user2 = "B";

    Console.WriteLine("user1: " + user1);
    Console.WriteLine("user2: " + user2);
}

public static void Main()
{
    string notUsed;
    CheckPasswords(out notUsed, out notUsed);
}

The console shows:

user1: B
user2: B
+4
source share
3 answers

It:

CheckPasswords(out notUsed, out notUsed);

notUsed ( , out), notUsed . . , notUsed , - , , out. :

user1 = "A";

- , user1 string - out string. , user1, , user1 - notUsed. notUsed "A". :

user2 = "B";

, - "B" notUsed. :

Console.WriteLine("user1: " + user1);
Console.WriteLine("user2: " + user2);

- , notUsed, user1 user2. , "B".

, :

class User {
    public string Name { get; set; }
}

void NotMagic(User user1, User user2) {
    user1.Name = "A";
    user2.Name = "B";

    Console.WriteLine("user1.Name = " + user1.Name);
    Console.WriteLine("user2.Name = " + user2.Name);
}

void Main() {
    User user = new User();
    NotMagic(user, user);
}

, , B. , NotMagic, , . out ref, , .

+1

You pass the variable by reference. In addition, the assignment order in the method is significant - as indicated here, the variable will contain “B” at the end. If you cancel them, “A” will appear.

For comparison:

user1 = "A"; // notused now contains "A"
user2 = "B"; // notused now contains "B"
// method ends with the variable notused containing "B"

Versus:

user2 = "B"; // notused now contains "B"
user1 = "A"; // notused now contains "A"
// method ends with the variable notused containing "A"
+3
source

Source: https://habr.com/ru/post/1684619/


All Articles