|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
ref (C# Reference)
Updated: September 2008
The ref keyword causes arguments to be passed by reference. The effect is that any changes to the parameter in the method will be reflected in that variable when control passes back to the calling method.
Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not related; a method parameter can be modified by ref regardless of whether it is a value type or a reference type. Therefore, there is no boxing of a value type when it is passed by reference.
To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword. For example:
An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed. For more information, see out.
Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument. The following code, for example, will not compile:
Overloading can be done, however, if one method takes a ref or out argument and the other uses neither as in the following example:
Properties are not variables. They are actually methods, and therefore cannot be passed as ref parameters.
For information about how to pass arrays, see Passing Arrays Using ref and out (C# Programming Guide).
Passing value types by reference, as demonstrated earlier in this topic, is useful, but ref is also useful for passing reference types. This allows called methods to modify the object to which the reference refers because the reference itself is being passed by reference. The following sample shows that when a reference type is passed as a ref parameter, the object itself can be changed. For more information, see Passing Reference-Type Parameters (C# Programming Guide).
For more information, see the following sections in the C# Language Specification:
5.1.5 Reference parameters
10.6.1.2 Reference parameters