09 November 2012

ref v/s out in .NET

In many technical interviews for the .NET Developer role, people ask what is the difference between the ref and out keywords?

OR

The same interview question might be twisted and asked like "when to use ref and out keywords?"

Often its confusing which keyword to use when writing a method which takes in value type parameter and changes the value. The confusion is .NET has two keywords for the purpose.

  1. out keyword
  2. ref keyword

Let's start out keyword with an example:

namespace OutKeywordExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int value = 1;
            bool valid = Process(out value);
        }
        static bool Process(out int value)
        {
            return true;
            // Compilation error here: The out parameter 'value' 
            // must be assigned to before control 
            // leaves the current method
        }
    }
}
When the above code is built, it fails with the below error:

The out parameter 'value' must be assigned to before control leaves the current method.

Error can be resolved by assigning a value to the out parameter inside the Process() method body.

Let's start ref keyword with an example:

namespace RefKeyWordExample
{
class Program
    {
        static void Main(string[] args)
        {
          int value;
          bool valid = Process(ref value);
          // Compilation error here: 
          // Because Use of unassigned local ref variable 'value'
        }
        static bool Process(ref int value)
        {
            return true;
        }
    }
}

When built, it fails to compile with the error below:

Use of unassigned local ref variable 'value'.

Error can be resolved by assigning a value to the integer variable before invoking the Process() method. So now we got to know the syntactical difference between the out and ref keywords.

  1. When out parameter is declared in the method declaration, the method body should assign a value to the out variable before returning. So its the responsibility of the callee to assign the value to the out parameter before it returns.
  2. Whereas when ref parameter is declared in the method, the argument being passed while invoking the method should have got the value assigned. So its the responsibility of the caller to assign the value for the ref argument before calling the method.

Example for the out keyword in .NET framework:

public static bool TryParse(string s,out DateTime result)

Example of the ref keyword in .NET framework:

public static double Exchange(ref double variable1, double value)

Summary:

  1. Use the out parameter for value types, if callee method should assign a value to a parameter before returning.
  2. Use the ref parameter for value types, when caller has already assigned value to a parameter even before invoking the method. The method body can modify the ref argument value, but there is no restriction as such.