ref
and out
parameters are quite similar in their meaning. ref
and out
keywords are used to pass parameters to a method by reference. By default parameters are being passed to methods by value. Passing reference to variable instead of value means referenced variable might (or must) be modified/assigned by the method accepting this reference. The main difference is out
parameters must be set during the execution of the method and ref
parameters are not required to be set before returning. But there is more.
First of all out
parameter doesn't need to be initialized before passing it to the method, because it will be initialized or set to new value by the method accepting it. Code where out
parameter hasn't been set in method's body simply won't compile. Contrary, ref
parameter should be initialized before passing it to a method. As such, the called method is not required to set ref
parameter before using it.
Also, there is difference in semantic meaning between these two keywords. They both allow called method to modify a parameter. Any changes made to the parameter will be reflected in the variable which parameter refers to. But, since ref
parameter should be set before passing it to a method and also might be changed in this method, it can be considered both input and (optionally) output of it. out
parameter can't be considered input, because it's not required to be initialized before passing it to a method. Such parameters are strictly output parameters. We can think of them as an additional return value of a method that is already using the return value for something.
Code examples:
public static void MethodWithOutParameter(out int id) { id = 1; } static void Main(string[] args) { int i; MethodWithOutParameter(out i); Console.WriteLine(i); } Output: 1
public static void MethodWithRefParameter(ref int id) { id = id + 1; } static void Main(string[] args) { int i = 1; MethodWithRefParameter(ref i); Console.WriteLine(i); } Output: 2
Short answer
- Both
out
andref
keywords are used in C# to pass parameters to methods by reference, which allows method to modify referenced variable. ref
parameter should be initialized before passing it, forout
parameters it's optional.out
parameter should be set in method's body, forref
parameters it's optional.- Use
ref
parameters as input/output of a method, useout
parameters as an additional returning value of it.
Comments