Ref vs Out in C#

I am in the process of interviewing contractors at work right now and have had the opportunity to ask one of my favorite C# questions:

What is the Difference Between Ref and Out in C#?

To my continued surprise, I have yet to have an interview candidate answer correctly. When I confront them with the question, most candidates will start to confuse pass by reference with pass by value, even though I tell them that both keywords are used for pass by reference. Or they’ll tell me that they’ve used out in some methods but don’t know why.

Grant it — in my opinion, having both keywords is extraneous. In Java, all objects are passed by reference without distinction. Similarly, C++ does not distinguish between the means of reference. C# requires a keyword to pass by reference. But people get confused because there are TWO keywords and BOTH pass by reference.

My guess is that Microsoft probably assumed they were making life easier for the programmer by providing both keywords for pass by reference. The keyword distinction allows the .Net compiler to assure that an argument is initialized/set prior to passing it into the method in the ref case. Or initialized/set inside the method in the out case.

In other words, the difference is that ref requires that an argument be initialized BEFORE being passed into a method. out does not require prior initialization, BUT does require that the implementation of a method set or initialize the argument. BOTH words are used for pass by reference.

I will demonstrate the difference between ref and out by means of some code:

using System;

public class Program
   static void Main(string[] args)
     var x = 5;
     Console.WriteLine("Result of PassByValue is: {0}", x);

     x = 5; // re-initialize to show nothing funny happening
     PassByRef(ref x);
     Console.WriteLine("Result of PassByRef is: {0}", x);

     x = 5; // not needed -- just for demonstration
     PassByOutRef(out x);
     Console.WriteLine("Result of PassByOutRef is: {0}", x);

   static public void PassByValue(int x)
     x += 5;

   static public void PassByRef(ref int x)
     x += 5;

   static public void PassByOutRef(out int x)
     x = 3; // required to re-initialize ds in order to compile
     x += 5;

And here is the result:

Pass By Ref vs Out Result

Result of Pass by Ref vs Pass by Out Demo

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s