Out and Ref
parameters in c#
Out and ref parameter used to return multiple values from
function in the form of parameter.
Ref Parameter:
Ref parameter passes the argument as a reference. In Ref
parameter reference of parameter passes to the called method by using Ref
Keyword. When the value of ref parameter changes in the called method, the new
value is updated in called method. In Ref parameter case you have to initialize
parameter before passing to called method.
Out Parameter:
Out parameter passes the argument as a value. In Out
parameter there is no need to initialize argument before passing to called
method.
See below example.
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int val1
= 1,
val2;
RefParameter(ref val1);
OutParameter(out val2);
Console.WriteLine(val1);
Console.WriteLine(val2);
Console.ReadLine();
}
public static void RefParameter(ref
int i)
{
i
= 10;
}
public static void OutParameter(out
int i)
{
i
= 12;
}
}
}
Output:
10
12
In the above program, for reference parameter we have passed
value to it 10. And after method the value is changed to 12. But in the case of
out parameter no need to initialize value but in out parameter you must have to
initialize variable in called method. In case of ref parameter it’s not
mandatory to initialize in called method
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int val1 = 1,
val2;
RefParameter(ref val1);
OutParameter(out val2);
Console.WriteLine(val1);
Console.WriteLine(val2);
Console.ReadLine();
}
public static void RefParameter(ref
int i)
{
}
public static void OutParameter(out
int i)
{
i
= 12;
}
}
}
Output:
1
12
0 Comments