What are you referring to Wilbur? (Passing classes by reference in C#)

June 20, 2013

I found this test project while doing a spring clean, and thought it would be ripe for a blog post.  To illustrate the problem that this is trying to address, I’m going to introduce you to two characters: Wilbur and Wright.  Wilbur is an enthusiastic junior developer just out of college, and Wright is a cranky old goat who’s been in the industry too long (these characters are not based on anyone I might know, have known or ever will know - so put that lawsuit down and keep your hands where I can see them).

Wilbur: What the…?  I’ve just tried to change this class inside a function and it doesn’t change! Wright: What do you mean “change this class”? Wilbur: I want to alter the class from what it was to something else, and it doesn’t work - why not? Wright:  Show me the code then!



    class MyFunkyClass
    {
        public int MyNumber { get; set; }
    } 

    class Program
    {
        MyFunkyClass testClass =newMyFunkyClass(); 
        testClass.MyNumber =10; 

        Console.WriteLine("Call ChangeClass()"); 
        ChangeClass(testClass); 
        Console.WriteLine("After ChangeClass(): {0}", testClass.MyNumber); 

        staticvoidChangeClass(MyFunkyClass myclass) 
        { 
            myclass =newMyFunkyClass(); 
            myclass.MyNumber =3; 
        }
    }


Wilbur: See, it doesn’t change - it starts at 10, and finishes at 10. Wright: You need to pass by reference if you’re going to change it! Wilbur: No I don’t - this works - it prints 20, which is correct:



        staticvoidMain(string[] args) 
        { 
            MyFunkyClass testClass =newMyFunkyClass(); 
            testClass.MyNumber =10; 
 
            Console.WriteLine("Call ChangeNumber()"); 
            ChangeNumber(testClass); 
            Console.WriteLine("After ChangeNumber(): {0}", testClass.MyNumber); 
        }

        staticvoidChangeNumber(MyFunkyClass myclass) 
        { 
            myclass.MyNumber +=10; 
        } 


Wright: You’re not changing the class, you’re changing a property. You’re passing the address of the class. If you intend to change the address of the class, then you need to pass that by reference, like this:


        ...
            Console.WriteLine("Call ChangeClassRef()"); 
            ChangeClassRef(ref testClass); 
            Console.WriteLine("After ChangeClassRef(): {0}", testClass.MyNumber); 
        }

        static void ChangeClassRef(refMyFunkyClass myclass)
        {
            myclass = new MyFunkyClass();
            myclass.MyNumber = 5;
        }

Wilbur: Let’s have a look what the difference is in the IL. Here’s mine:



.method private hidebysig static void  ChangeClass(class ConsoleApplication2.MyFunkyClass myclass) cil managed
{
  // Code size       17 (0x11)
  .maxstack  8
  IL\_0000:  nop
  IL\_0001:  newobj     instance void ConsoleApplication2.MyFunkyClass::.ctor()
  IL\_0006:  starg.s    myclass
  IL\_0008:  ldarg.0
  IL\_0009:  ldc.i4.3
  IL\_000a:  callvirt   instance void ConsoleApplication2.MyFunkyClass::set\_MyNumber(int32)
  IL\_000f:  nop
  IL\_0010:  ret
} // end of method Program::ChangeClass


Wilbur: And here’s yours:



.method private hidebysig static void  ChangeClassRef(class ConsoleApplication2.MyFunkyClass& myclass) cil managed
{
  // Code size       18 (0x12)
  .maxstack  8
  IL\_0000:  nop
  IL\_0001:  ldarg.0
  IL\_0002:  newobj     instance void ConsoleApplication2.MyFunkyClass::.ctor()
  IL\_0007:  stind.ref
  IL\_0008:  ldarg.0
  IL\_0009:  ldind.ref
  IL\_000a:  ldc.i4.5
  IL\_000b:  callvirt   instance void ConsoleApplication2.MyFunkyClass::set\_MyNumber(int32)
  IL\_0010:  nop
  IL\_0011:  ret
} // end of method Program::ChangeClassRef


Wilbur: So what’s the difference? Wright: You called your app ConsoleApplication2!? WTF? Wilbur: Hey, these posts take a while to wright, Wright! Anyway, you haven’t answered. Wright: Well, it’s been a while, but thinking back to my C days, doesn’t the ampersand (&) mean address of? Wilbur: Are you telling me or asking me? Wright: If I pass the address of the class, I can change the class, because I simply change the address that it points to, but if I pass the class itself, I don’t have that reference, I only have the class. Make sense? Wilbur: No. Wright: Okay, think of it like this. Say you go to an estate agent, and they show you around a nice three bed semi-detached. While you’re in the house, you ask the agent if they could move the house three streets away. That’s what you’re doing when you don’t pass the class by reference.

Now, imagine that instead of taking you to the house, the estate agent gives you a piece of paper with the address of the house on. If you want a house three streets away, you simply overwrite what’s written on the paper with the new address.

THE END



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024