Both the ref and out parameters are basically used to return values with the same variables that is passed as an argument to a method. But the difference is that the variable passed as an out parameter need not be initialized and is exclusively used for returning data to the caller whereas a variable passed as a ref parameter should be initialized and is used to pass as well as receive data from the method.
Eg:
For Passing by reference
static void Main(string[] args)
{
int i, j; //Should be initialized
i = 3;
j = 4;
PassByRef(ref i, ref j);
Console.WriteLine(i);
Console.WriteLine(j);
}
static void PassByRef(ref int var1, ref int var2)
{
var1 += 3;
var2 += 4;
}
Output is i=6, j=8
For Passing as Out
static void Main(string[] args)
{
int i, j; //Need not be initialized
PassByOut(out i, out j);
Console.WriteLine(i);
Console.WriteLine(j);
}
static void PassByOut(out int var1, out int var2)
{
var1 = 10;
var2 = 20;
}
Output is i=10, j=20
Thursday, November 20, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment