1

I'm trying to execute the following code and can't understand why don't the line person.Name = "anton"; work? The output of the program is "colin".

class Person
{
    public string Name;
}

class MainClass
{
    public static void MyMethod(Person person)
    {
        person.Name = "colin";
        person = new Person();
        person.Name = "anton";
    }

    public static void Main()
    {
        Person person = new Person();
        person.Name = "felix";
        MyMethod(person);
        Console.WriteLine(person.Name);
    }
}
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
martikyan
  • 154
  • 10

2 Answers2

2

Think of the sequence of events that happen:

  • Main creates a Person
  • Main passes a reference to Person into MyMethod
  • MyMethod makes a modification to Main's Person. This is modification #1
  • MyMethod replaces the reference to the object from Main with a reference to a new Person object. At this point, Main's person variable and MyMethod's person parameter are referencing two different objects.
  • MyMethod modifies its Person object (modification #2), and returns
  • Main's person shows the result of the first modification, before the object has been replaced by MyMethod's invocation of new.

If you would like to permit reassignments to person inside MyMethod, you need to pass the variable by reference.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Unless you specify the ref or out keyword, function parameters are passed by value in C#, even if the type is a reference type.

"Passing by value" means creating a copy of the original variable, which for reference types means the copy of the reference (not the actual object, the object is not copied, and is simply "pointed to" by both the variable and the parameter).

This means that the person parameter inside MyMethod is a copy of the person variable from the Main method, so assigning a new instance to this parameter won't affect the original variable.

So changing the properties of the instance inside the function will affect the original instance, until the parameter starts pointing to a different object (the point where you instantiate a new Person inside MyMethod).

vgru
  • 49,838
  • 16
  • 120
  • 201