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.


To Var or Not To Var

This is obviously a highly debated topic that doesn’t have a clear right or wrong answer to it.  The use of the keyword var allows you to implicitly define a type.  An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

For example:

var item = “table”;  //implicitely typed
string item = “table”; // explicitly typed

Some reasons that I have come across that people favor var for are that it reduces the amount of code and the time that it takes to code it. It makes sense; you use var, type your variable name and move on.  However, there are some drawbacks that can arise.  Say that you do not use a very descriptive variable naming.

var myCar = new Car(); //Clear
var i = myCar.GetSomething(); //Not Clear what i would be

So if I am a developer coming back to the code or it is within code I did not write, I am going to have to hover over it to see what exactly is returned. Time is ended up being saved in the coding aspect of it, but when bugs/enhancement/etc come up and the code goes through another read through time is lost deciphering types and variables due to poor naming conventions and var being used so loosely.

Linq does require var to be use when using on anonymous type.

var employeeQuery = from employee in company
                    where employee.Location == "USA"
                    select new { employee.Name, employee.Phone };

Since we are using an anonymous type, var is used.

However, say we have a type. Notice how it is a bit longer, but now I know exactly what my end result is and there is no question as to what the outcome is.

IEnumerable<Employee> employeeQuery = from employee in company
                                      where employee.Location == "USA"
                                      select employee;

It really seems to come down to is having a group standard from within your team.  Personally, I use explicit typing so that there is no question and I know exactly what type is going to be chosen at compile time.  As well, future developers will know exactly what my intent was and not have to try and guess what I was aiming for or simply being lazy.

Thoughts? What are your coding standards?


StackOverflow Profile