ref (C# Reference) 

The ref keyword causes arguments to be passed by reference. The effect is that any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword. For example:

class RefExample
{
    static void Method(ref int i)
    {
        i = 44;
    }
    static void Main()
    {
        int val = 0;
        Method(ref val);
        // val is now 44
    }
}

An argument passed to a ref parameter must first be initialized. This differs from out, whose argument need not be explicitly initialized before being passed. (See out.)

Although ref and out are treated differently at run-time, they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument. These two methods, for example, are identical in terms of compilation, so this code will not compile:

class CS0663_Example 
{
    // compiler error CS0663: "cannot define overloaded 
    // methods that differ only on ref and out"
    public void SampleMethod(ref int i) {  }
    public void SampleMethod(out int i) {  }
}

Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this:

class RefOutOverloadExample
{
    public void SampleMethod(int i) {  }
    public void SampleMethod(ref int i) {  }
}

Remarks

Properties are not variables and therefore cannot be passed as ref parameters.

For information on passing arrays, see Passing Arrays Using ref and out.

Example

Passing value types by reference--as demonstrated above--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.

class RefRefExample
{
    static void Method(ref string s)
    {
        s = "changed";
    }
    static void Main()
    {
        string str = "original";
        Method(ref str);
        // str is now "changed"
    }
}

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 5.1.5 Reference parameters

  • 10.5.1.2 Reference parameters

See Also

Reference

Passing Parameters (C# Programming Guide)
Method Parameters (C# Reference)
C# Keywords

Concepts

C# Programming Guide

Other Resources

C# Reference