Wednesday, July 8, 2009

C# allows Passing Parameters by reference

By default CLR assumes that all the parameters to a method are value type.
C# allows pass parameter by reference type in two ways
  1. Ref :The caller must initialized the parameter's value to the method
E.g: Public static void RefAni(ref int iVal)
{
iVal+=2;
}
public static void Main()
{
int i=3; //i must be intialized
RefAni(ref i);
Console.Writeline(i);
}
Note : The i value is declared on the thread stack and initialized to 3.Address location of i is passed to RefAni method. RefAni iVal takes the value and new value is returned to the caller.
2.Out: The caller must not have to be initalized the parameter's value to the method
E.g:
Public static void OutAni(out int iVal)
{
iVal+=2;
}
public static void Main()
{
int i; //doesnot have to be intialized
OutAni(out i);
Console.Writeline(i);
}

Note : the i is declared on the thread stack .The address is then passed to the OutAni(here no values are comming).Inside the OutAni iVal is initailized to 2 and new value is returned to the caller.

Why ref and out is required ?
This is that the compailer want to do the right thing automatically.

Note : overloading is possiblie in this

E.g : Public static void OutAni(out int iVal)
Public static void OutAni(int iVal)
This will compile properly.

0 comments:

 
Counter