Difference Between Ref and Out

The difference between ref and out may not be complicated but easy to mix up. This is really a post mainly for my quick reference and knowledge, but hey, it might pose a quick use for someone else too.

Ref is a keyword that causes an argument to be passed by reference, not by value.  This has an effect of when there is any change to the parameter in the method is reflected in the underlying argument variable in the calling method.   When using the ref keyword, you must use it in the method definition and in the calling method.

class ExampleForRef
{
    static void Main()
    {
        int val = 23;
        RefMethod (ref val);
        Console.WriteLine(val);

        // i = 46
    }

    static void RefMethod(ref int i)
    {
        i = i + 23;
    }
}

A ref parameter must also be initialized before it is passed.  This is a difference between ref and out because when using the out keyword, the variable does not have to be initialized before it is passed.[more]

Out is a keyword that causes arguments to be passed by reference.  This is very similar to what we just discussed above, but when using out, the variable must be initialized before it gets passed. In order to use the out parameter, the method definition and the calling method both must explicitly use the out keyword.

class ExampleForOut
{
    static void Main()
    {
        int value;
        Method(out value);

        // value is now 44
    }

    static void Method(out int i)
    {
        i = 44;
    }
}

A few notes to keep in mind. The called method is required to assign a value before the method can return.  In terms with compiling issues with overloading that may arise, the methods cannot be overloaded if the only difference is the ref and the out. This is taken from msdn:

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) { }
}

However, if the ref or out parameter is only used in one method than it can be accomplish like this:

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

class OutOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(out int i) { i = 5; }
}

Some ending notes from my research:
-There is no boxing when a value type is passed by reference.
-Properties cannot be passed by ref or out, properties are really methods.


Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile