Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Passing same variable to two "out" parameters

Tags:

c#

Is it normal that 'user1' and 'user2' point to the same reference in the example below?

I know that I am passing the same variable 'notUsed' to both parameters, but it's not yet instanced so it does't contain a reference to anything. I was quite shocked to see that user1 and user2 are linked 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);
}

Console shows:

user1: B
user2: B
like image 785
John Avatar asked Dec 07 '22 17:12

John


1 Answers

When you use the out keyword, you pass by reference. (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier) Since you are passing by reference, your user1 and user2 are both pointing to the same variable. Hence, when you update one, it updates the other.

like image 194
Michael Sharp Avatar answered Dec 22 '22 23:12

Michael Sharp