Monday, May 27, 2013

What is the difference between a ref and out keyword? (C#)

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. For example:
class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value; Method(out value);
        // value is now 44     }
}

class RefExample
    {
        static void Method(ref int i)
        {
           // The following statement would cause a compiler error if 'i' were boxed as an object.            

 i = i + 44;
        }
        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);
            // Output: 45         }
    }
Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

The ref and out keywords are treated differently at run-time, but 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(out int i) {  }
    public void SampleMethod(ref 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(out int i) {  }
}

No comments: