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


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 ed 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 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 ed 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 ed 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 ed 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 ed by reference. This is similar to the refkeyword, except that ref requires that the variable be initialized before being ed. 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 value(out int val)
        {
           val = 20;
        }
    static
void Main(string[] args)
        {
            int value;
            value(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 ed 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 ed.
 
For example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace outexample
{
    class Program
    {
        static void value(ref int val)
        {
           val = 20;
        }
    static
void Main(string[] args)
        {
            int value;
            value(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 ed.
 
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 value(ref int val)
        {
           val = 20;
        }
    static
void Main(string[] args)
        {
            int value = 10;
            value(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 value(out int i) { }
        public void value(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 value(int i) {  }
        public void value(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 value(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;
            value(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 ed as out parameters.

Final conclusion:

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

Up Next
    Ebook Download
    View all
    Learn
    View all