Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

ref

The ref method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. 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, the argument must explicitly be passed to the method as a ref argument. The value of a ref argument will be passed to the ref parameter.

An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.

A property is not a variable and cannot be passed as a ref parameter.

An overload will occur if declarations of two methods differ only in their use of ref. However, it is not possible to define an overload that only differs by ref and out. For example, the following overload declarations are valid:

class MyClass 
{
   public void MyMethod(int i) {i = 10;}
   public void MyMethod(ref int i) {i = 10;}
}

but the following overload declarations are invalid:

class MyClass 
{
   public void MyMethod(out int i) {i = 10;}
   public void MyMethod(ref int i) {i = 10;}
}

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

Example

// cs_ref.cs
using System;
public class MyClass 
{
   public static void TestRef(ref char i) 
   {
      // The value of i will be changed in the calling method
      i = 'b';
   }

   public static void TestNoRef(char i) 
   {
      // The value of i will be unchanged in the calling method
      i = 'c';
   }

   // This method passes a variable as a ref parameter; the value of the 
   // variable is changed after control passes back to this method.
   // The same variable is passed as a value parameter; the value of the
   // variable is unchanged after control is passed back to this method.
   public static void Main() 
   {
   
      char i = 'a';    // variable must be initialized
      TestRef(ref i);  // the arg must be passed as ref
      Console.WriteLine(i);
      TestNoRef(i);
      Console.WriteLine(i);
   }
}

Output

b
b

See Also

C# Keywords | Method Parameters

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft