SIGN UP MEMBER LOGIN:    
ARTICLE

Work with "out" and "ref" keywords in C#

Posted by Akshay Teotia Articles | C# Language November 15, 2011
The out and ref keyword look quite similar in nature. Both parameters are used to return back some value to the caller of the function. But still there is a small but important difference between them. Both of the parameter type has been kept in the C# language for specific scenario.
Reader Level:

Introduction

In C Sharp (C#) we can have three types of parameters in a function. The parameters can be In parameter (which is not returned back to the caller of the function), out parameter and ref parameter (where by a reference to the variable is passed back).

The first thing that we will take a look at, is the out and ref modifiers. C#, and other languages as well, differ between two parameters: "by value" and "by reference". The default in C# is "by value", which basically means that when you pass on a variable to a function call, you are actually sending a copy of the object, instead of a reference to it. This also means that you can make changes to the parameter from inside the function, without affecting the original object you passed as a parameter.

Consider the following example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace simplevalue
{
    class Progra
 {
      static void Addvalue(int val)
        {
             val++
        }
      static
void Main(string[] args)
       {
            int
value = 10;
            Addvalue(value);
            Console.WriteLine(value);
            Console.Read();
        }
    }
}

Output: 10

We create an integer, assign the number 10 to it, and then we use the Addvalue() method, which should add 1 to the number. But does it? No. The value we assign to number inside the function, is never carried out of the function, because we have passed a copy of the number value instead of a reference to it. This is simply how C# works, and in a lot of cases, it's the preferred result. However, in this case, we actually wish to modify the number inside our function. Enter the ref and out keyword:

The out and ref keyword are looks quite similar in nature. Both parameters are used to return back some value to the caller of the function. But still there is a small but important difference between them. Both of the parameter type has been kept in the C# language for specific scenario.

"out" keyword  

The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.

The out keyword causes arguments to be passed by reference. This is similar to the refkeyword, except that ref requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

For example:
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace outexample
{
    class Program
    {
        static void passvalue(out int val)
        {
           val = 20;
        }
    static
void Main(string[] args)
        {
            int value;
            passvalue(out value);
            Console.WriteLine(value);    
           Console.Read();
        }
    }
}

Output: 20

When we use the out parameter, The program calling the function need not assign a value to the out parameter before making the call to the function. The value of the out parameter has to be set by the function before returning the value.

"ref" keyword

The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.

The ref keyword is similer to out keyword but ref requires that the variable be initialized before being passed.
 
For example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace outexample
{
    class Program
    {
        static void passvalue(ref int val)
        {
           val = 20;
        }
    static
void Main(string[] args)
        {
            int value;
            passvalue(ref value);
            Console.WriteLine(value);    
           Console.Read();
        }
    }
}

when we build this code it will fire an error "use of unassigned local variable 'value' " the resion is behind that the ref requires that the variable be initialized before being passed.
 
To run above program properly just initialized the value (variable).

For example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace outexample
{
    class Program
    {
        static void passvalue(ref int val)
        {
           val = 20;
        }
    static
void Main(string[] args)
        {
            int value = 10;
            passvalue(ref value);
            Console.WriteLine(value);    
           Console.Read();
        }
    }
}

Output: 20

Some more useful facts about ref and out keyword

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 Program
    {|
        // compiler error CS0663: "cannot define overloaded
        // methods that differ only on ref and out"
        public void passvalue(out int i) { }
        public void passvalue(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 Program
    {
        public void passvalue(int i) {  }
        public void passvalue(out int i) {  }
    } 

Declaring an out method is useful when you want a method to return multiple values. A method that uses an out parameter can still a variables as a return type (see return) but it can also return one or more objects to a calling method as out parameters. This example uses out to return three variables with a single method call. Note that the third argument is assigned to null. This allows methods to return values optionally.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace outexample
    class Program
    {
         static void passvalue(out int i,out string s1,out string s2)
         {
          i=20;
          s1="I've been returned";
          s2=null;
        
         }
       
        static void Main(string[] args)
        {
            int v;
            string str1,str2;
            passvalue(out v,out str1,out str2);
            Console.WriteLine(v +" " + str1 +" "+ str2);
            Console.Read();
        }
    }
}

Output: 20 I've been returned

Properties are not variables and therefore cannot be passed as out parameters.

Final conclusion:

The out and the ref parameters are used to return values in the same variables, that you pass an argument of a method. These both parameters are very useful when your method needs to return more than one values.

Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Become a Sponsor