Search code examples
c#reference-type

Reference types as value and reference parameters


So Im going through Illustrated C# 2012, I basically get everything but this section of the chapter, below is the source code:

class MyClass
{
    public int Val = 20;
}

class Program
{
    static void RefAsParameter(MyClass f1)
    {
        f1.Val = 50;
        Console.WriteLine( "After member assignment: {0}", f1.Val );
        f1 = new MyClass();
        Console.WriteLine( "After new object creation: {0}", f1.Val );
    }

    static void Main()
    {
        MyClass a1 = new MyClass();
        Console.WriteLine( "Before method call: {0}", a1.Val );
        RefAsParameter( a1 );
        Console.WriteLine( "After method call: {0}", a1.Val );
    }
}

This code produces the following output:

Before method call: 20
After member assignment: 50
After new object creation: 20
After method call: 50

So... I understand basically most of it up to the last Console.WriteLine(). why is it 50 "after method call". Since it created a new "MyClass()" shouldn't it still be 20? Clearly im missing something majorly obvious. Is it because f1.Val changed the Myclass Public value "for good" or what?

Slightly confused on this. Thanks. I understand "references" in general this one im just kinda stumped on.


Solution

  • The line

    f1 = new MyClass();
    

    reassigns the variable f1 to point to a new MyClass. It does not change the a1 variable.

    If you change the method to this:

    static void RefAsParameter( ref MyClass f1 )
    

    Then it will change the a1 variable, and you will get:

    After method call: 20