Difference between out and ref parameter

Posted by Techie Cocktail | 2:04 PM | 0 comments »

The 'out' and 'ref' parameters are useful when you are required to get more than one return values.

Below are a few differences.

out parameter:
The out parameter is generally a variable passed as an argument to a
method by using the out keyword. Any value assigned to this variable
inside the method is reflected/returned to the out parameter.

The out parameter is not initialized when passed to the method.

With the use of out keyword to the variable, an additional
output value can be returned from a method as the output variable.


public class outClass
{
public static void OutMethod(out int x, out int y)
{
x = 1;
y = 2;
}
public static void Main()
{
int a, b;
Console.WriteLine(outMethod(out a, out b));
Console.WriteLine(a); //prints 1
Console.WriteLine(b); //print 2
}
}

ref parameter:
The ref keyword used for a variable passed to a method makes the same
instance of the variable being referred everywhere inside the method.
Any value assigned/updated inside the method, the same instance
value is being referred all over its use.

public class refClass
{
public static void refMethod(ref int x)
{
x = 10;
}
public static void Main()
{
int a;
a = 3;
refMethod(ref a);
Console.WriteLine(a); //prints 10.
}
}

0 comments