Both out and ref parameters are used to return values in the same variables that you would pass as an argument of a method. Both types of parameters can be useful in an event where you would like to return more than one value from your method.
Out Parameter
Briefly defined an out parameter can be used to return the values in the same variable passed as a parameter of the method. Coincidentally any changes made to the parameter will be reflected in the variable.
| public void foo(out int bar) |
| { |
| bar = 1; |
| } |
| |
| private void foobar() |
| { |
| int baz; //initialization of variable NOT required |
| foo(out baz); |
| Console.WriteLine(baz); |
| } |
Ref Parameter
Briefly defined the ref keyword used on a method parameter causes a method to refer to the same variable that is passed as an input parameter for the same method. Coincidentally any changes made to the parameter will be reflected in the variable.
In contrast to utilizing an out parameter utilizing the ref keyword on a method parameter requires that the value being passed as a parameter first be initialized.
| public void foo(ref int bar) |
| { |
| bar +=1; |
| } |
| |
| private void foobar() |
| { |
| int baz; |
| baz = 1; //initialization of variable required |
| foo(ref baz); |
| Console.WriteLine(baz); |
| } |