What is ref and out parameter in C#?

(Last Updated On: September 14, 2016)

Answer: Both ref and out parameter or keywords in C# are used to pass an argument as a reference to a method in C# program. For example,

public void X(ref int val)
public void Y(out int val)

The difference between ref and out parameters in C# is
The ref variable must be initialized before passing to a function. Whereas, there is no need to initialize out variable before passing it to function.However, if we initialize out variable before passing to method, there is no harm, but, it is useless, as we must initialize or assigned a value to out variable within the function body.

 

Example with comments:

 

Points:

  • Since, ref and out variables in C# are passed as a reference to a function, the value changed in function body will be reflected in calling function.
  • Also, ref is IN/OUT (Read/Write) parameter as we initialize it before passing to function, we can use the value or modify the value inside the function body.
  • And out is OUT (Write) parameter, means, only we can assign/write the value to it and cannot read the value before assignment if we have initiated before passing.