To pass an argument by reference in C# , we use the keyword ref . There is also another keyword “out” which can also be used to pass an argument by reference .
Below is a sample code demonstrating the usage of the out and ref keyword.
class Employee
{
/* usage of the pass by reference using the keyword out */
public void SQRT1(out int i)
{
i = 10;
i = i + i;
}
/* usage of the pass by reference using the keyword ref */
public void SQRT2(ref int i)
{
i = 10;
i = i + i;
}
}
class Program
{
public static void Main1()
{
Employee studentObj = new Employee();
int i;
studentObj.SQRT1(out i);
int j=1;
studentObj.SQRT2(ref j);
Console.WriteLine("i: " + i);
}
}
What is the difference between out and ref keyword in C# ?
The variable has to be initialized when it is passed by ref keyword . The variable need not be initialized when using the out keyword but the value should be assigned inside the calling function.
