Passing Reference Type by Value – a trap for the .NET programmers

Reference type can be passed as parameters to type members. Here programmers can fall into the trap, because passing an object by reference is quite different from passing it by value. To understand the distinction, examine the given example:

public class MyClass
     public int bar;
     public MyClass(int b) { bar = b; }

Below we created two methods that allows send the reference type by value (note the ref parameter modifier):

public static void SendRefByValue(MyClass oValue)
{ = 100; 
    oValue = new MyClass(72);

public static void SendRefByRef(ref MyClass oValue)
{ = 200; 
    oValue = new MyClass(72);

And of course we have to use the following class and static method:

static void Main(string[] args)
    MyClass oLocal_1 = new MyClass(16);
    Console.WriteLine("Value of bar field from object oLocal_1 after call SendRefByValue: {0}",;

    MyClass oLocal_2 = new MyClass(32);
    SendRefByRef(ref oLocal_2);
    Console.WriteLine("Value of bar field from object oLocal_2 after call SendRefByRef: {0}",;

What do you think, what will be the output? (click the image below to check)


Suprise is that after call SendRefByValue() method and pass oLocal_1 object just by Value, value of the bar has changed to new 100. Let’s explain what’s happens:

Value types are allocated on the stack. When we pass reference object by value (like in SendRefByValue() method) we copy the reference to the caller’s object – oValue. Passing reference type by value loks the reference in place – similar to constant pointers in C++. Therefore, as the method is pointing to the same object as the caller, it is posible to change the object’s state data (in our case: value of the bar).

In second case when we use SendRefByRef() method and pass reference type by the reference. Reference type areallocated on the managed heap. These object stay in memory until the .NET garbage collector destroy them. By default, assignment of reference types results in a new reference to the same object on the heap.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s