Sunday, September 14, 2008

Passing reference type ByVal or ByRef.

In .net framework there is two type set. One is reference type and another one is value type.

This post is about passing reference type by val or byref.

1. Passing ByVal.

Example:
class A
{
int i;
}


class bMain
{
public static void main()
{
A var = new A();
var.i = 10;
Console.WriteLine("Before Pass{0}",var.i);
TestFun(var);
Console.WriteLine("After Pass{0}",var.i);
}
public static void TestFun(A a)
{
a.i = 20;
}
}

output:
Before Passs : 10
After Pass: 20

Here you can see default behavior of reference type. When reference type pass by value then you can change member of that variable. But what happen when you try to reassign variable it self.

Please following code For TestFun

public static void TestFun(A a)
{
a = new A();
a.i = 20;
Console.WriteLine("Inside Fun: {0}",a.i);
}

Output:
Before Pass : 10
Inside Fun: 20
After Pass: 10

Because when reference type pass by value not actual reference is passed. Instead of that copy of reference is passed. When you try to update that parameter inself it will not take affect outside scope of function.

2. Passing By Ref.

class A
{
int i;
}


class bMain
{
public static void main()
{
A var = new A();
var.i = 10;
Console.WriteLine("Before Pass{0}",var.i);
TestFun(var);
Console.WriteLine("After Pass{0}",var.i);
}
public static void TestFun(ref A a)
{
a.i = 20;
}
}

output:
Before Pass : 10
After Pass :20

Now we update reference itself.
public static void TestFun(ref A a)
{
a = new A();
a.i = 20;
Console.WriteLine("Inside Fun {0}",a.i);
}
Output:
Before Pass: 10
Inside Fun: 20
After Pass: 20

Here actual reference is passed. So it will take affect outside function too.

You can get more detail at following location:
http://msdn.microsoft.com/en-us/library/0f66670z(vs.71).aspx#vclrfpassingmethodparameters_referencetypes

No comments: