Question

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.

Was it helpful?

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

OTHER TIPS

Behold.. my awesome paint skillz:

enter image description here

(Click here for the full image)

When f1 is used within the method, it is a new reference that points to the same object in memory. When you re-assign the reference with f1 = new MyClass();, you are effectively saying "okay, this reference now points to a new instance". This leaves a1 untouched.. so when the function unwinds and hits the Console.WriteLine, your a1 reference still references the old area of memory.. which now has a property set at 50.

To have the behaviour you expect, you pass the object in as a ref parameter:

static void RefAsParameter(ref MyClass f1)

When an object is referenced, it doesn't mean it is copying itself. It means we are pointing to the same object with two different names. Here a1 and f1 are both referencing the same object that's why if we are changing the value using f1 so the value is changing for a1 as well.

Later you are creating another instance and assigning the reference to f1. So now f1 will have no longer access to the previous object, and now a1 and f1 will not reference the same object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top