csharpbits

CSharp bits and bytes weblog

&
 

Apr 07 2009

Parameter Passing - To ‘ref’ or Not to ‘ref’ an Object

Published by sumedhahewagama at 9:00 am under C# snippets Edit This

For this article I am assuming a basic knowledge of c#. The ‘ref’ keyword is used to pass a parameter to a function by reference. So for example if we have a function like:

private void Swap(int num1, int num2)
{
 int temp = num1;
 num1 = num2;
 num2 = temp;
}

 

where the two parameters are passed by value, and if we call it with

int a = 10;
int b = 20;
Swap(a, b);

 

before and after the swap the variable ‘a’ will be 10, and ‘b’ will be 20. The values will not have changed.

However, if pass the parameters by reference

private void Swap(ref int num1, ref int num2)
{
 int temp = num1;
 num1 = num2;
 num2 = temp;
}

 

Now, after calling the Swap function, the values in the two variables will be swapped. But how about when we pass in a reference type variable instead of a value type variable? To experiment lets declare the following class:

class MyObject
{
 public int AnInt { get; set; }
 string name;
 public MyObject(string name)
 {
  this.name = name;
 }
 public void DisplayState()
 {
  Console.WriteLine(“{0} has value {1}”,
				name, AnInt);
 }
}
 

Lets us now define a function to exercise this class.

private void DoSomething(MyObject obj,
			MyObject obj2)
{
 Console.WriteLine(“Inside DoSomething()”);
 obj.AnInt = 100;

 

 obj2 = new MyObject(“New Second Object”);
 obj2.AnInt = 1000;
 obj2.DisplayState();
}

 

we will call this function like this

MyObject obj = new MyObject(“First Object”);
MyObject obj2 = new MyObject(“Second Object”);

 

obj.AnInt = 1;
obj.DisplayState();

 

obj2.AnInt = 2;
obj2.DisplayState();

 

DoSomething(obj, obj2);

 

obj.DisplayState();
obj2.DisplayState();

 

Console.ReadLine();

 

As you see both parameters are passed in without the ref keyword. But unlike the previous value types that were passed in, the member variable in the “First Object” object is retained after the execution of the function. This is because we passed in a reference to an object. So, what we have actually changed is the actual value of the original object, since we passed in a reference and not a copy. However we still cannot change the reference that we passed in (we cannot point obj2 to an entirely new object), as apparent when we perform a ‘new’ operation on obj2. This time we are changing the reference to the actual object. Thus the original object will remain when we return from the function. To make obj2 point to the ‘new’ object and for it to retain its value after returning from the function we will have to modify the parameter to add the ref keyword (private void DoSomething(MyObject obj, ref MyObject obj2)).

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
Possibly-related Articles:                                        (auto-generated)

Trackback URI | Comments RSS

Leave a Reply