Thursday, March 1, 2012

Difference between ref and out parameters in .NET


The out and the ref parameters are used to return values in the same variables, that you pass an an argument of a function. These both parameters are very useful when your function needs to return more than one values.


                The out Parameter
The out parameter can be used to return the values in the same variable passed as a parameter of the function. Any changes made to the parameter will be reflected in the variable.

public class mathClass
{
public static int ExampleFunction(out int integerValueFrist, out int integerValueSecond)
{
integerValueFrist = 10;
integerValueSecond = 20;
return 0;
public static void Main()
{
int var1, var2; // variable need not be initialized
Console.WriteLine(ExampleFunction(out i, out j));
Console.WriteLine(var1);
Console.WriteLine(var2);
}
}

        The ref parameter
The ref keyword on a function parameter causes a function to refer to the same variable that was passed as an input parameter for the same function. If you do any changes to the variable, they will be reflected in the variable. We can even use ref for more than one function parameters.

namespace TestRefP
using System; 
public class myClass 
public static void ExampleFunction(ref int integerValueFrist ) 
integerValueFrist += 2; 
public static void Main() 
int variable; // variable need to be initialized 
variable = 3; 
ExampleFunction(ref variable ); 
Console.WriteLine(variable); 
}


Before calling


[ref]:  Called must set the value of the parameter before passing it to the Called method.


[out]:  caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded.


During the call:


[ref]:  Called method can read the argument at any time.


[out]:  Called method must initialize the parameter before reading it.




Difference 
An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.




Example :


Ref (initialize the variable) 
int getal = 0; 
Fun_RefTest(ref getal); 


Out (no need to initialize the variable) 
int getal; 
Fun_OutTest(out getal); 



Check out Following Video for better understanding :










No comments:

Post a Comment

Live

Your Ad Here