Labels

Monday, December 10, 2007

Swap Myth - Value/Refrence Type

In the interview if I ask a simple question – How swap of Value and Referecne type works. Outcome is always unsatisfactory.

Here is the myth.

Suppose you have two Value types and two Reference Types. Lets try to swap them.

Value Types –

string str1 = "Hello";

string str2 = "World";

MessageBox.Show("Before Change: " + str1 + "," + str2); // Hello World

SwapMe( str1, str2);

MessageBox.Show("After Change: " + str1 + "," + str2); // Hello World [Does not works]

· The values of the parameters is passed as ‘By Value’.

· Hence swapping did not worked.

· To success, need to pass the value types By Reference using the ‘ref’ keyword.

SwapMe(ref str1, ref str2);

Reference Types –

Employee obj1 = new Employee(5);

Employee obj2 = new Employee(6);

MessageBox.Show("Before Swap: " + obj1.i.ToString() + "," + obj2.i.ToString()); // 5, 6

Swap.SwapMe(obj1, obj2);

MessageBox.Show("After Swap: " + obj1.i.ToString() + "," + obj2.i.ToString()); // 5, 6 [Does not works]

· Before we proceed, just notice that the value of the parameter is the address of the object (Pointer to the object) and not the value of object.

· The address is passed as ‘By Value’ and not ‘By Reference’. (Might be feeling strange).

· Hence swapping the address would not affect the actual addresses.

· But if you need to do this, pass it using ‘ref’.

Swap.SwapMe(ref obj1, ref obj2);

But at the same time instead of swapping if you want to change the values as below, then it will work perfectly fine without the use of ‘ref’ keyword.

Employee obj1 = new Employee(5);

Employee obj2 = new Employee(6);

MessageBox.Show("Before Swap: " + obj1.i.ToString() + "," + obj2.i.ToString()); // 5, 6

ChangeMe s(obj1, obj2);

MessageBox.Show("After Swap: " + obj1.i.ToString() + "," + obj2.i.ToString()); // 6, 5 [Does works]

· As above described value of the parameter is the address of the object (Pointer to the object) and not the value of object.

· The address is passed as ‘By Value’ and not ‘By Reference’.

· But code is dereferencing the objects and then changing its value.

· Hence it will change to the actual object, without the need of using ‘ref’.

Supporting fucntions:

// public static void SwapMe(ref Employee a, ref Employee b)

public static void SwapMe(Employee a, Employee b)

{

Employee temp;

temp = a;

a = b;

b = temp;

}

//public static void SwapMe(ref string a, ref string b)

public static void SwapMe(string a, string b)

{

string temp;

temp = a;

a = b;

b = temp;

}

public static void ChangeMe(Employee a, Employee b)

{

a.i = 55;

b.i = 66;

}

Thanks & Regards,

Arun Manglick || Tech Lead

No comments:

Post a Comment