Ref vs Out

Difference between ref and out parameters in C#

Difference between ref and out parameters

Till now we have discussed regarding Difference between Var and Dynamic in c#Difference between Hashtable and Dictionary , Scheduler for multiple instances in C#Constant vs ReadOnly in C# etc. Today we will discuss regarding Difference between ref and out parameters in C# with example and also look into Polymorphism with them.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method.

The argument must be initialized before passing into method.

 

Example:

class Test
{
    static void Main(string[] args)
    {
        int iRef = 0; //must be initialized
        Example1(ref iRef);
        Console.WriteLine(iRef);
    }

    private static void Example1(ref int iRef)
    {
        // iRef can be assigned again or can not be.
    }
}
// Output: 0

 

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it.

An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

class Test
{
    static void Main(string[] args)
    {
        int iOut = 0; // May be initialize or may be not.
        Example1(out iOut);
        Console.WriteLine(iOut);
    }

    private static void Example1(out int iOut)
    {
        iOut = 10; // iOut must be assigned
    }
}
// Output: 10

 

Ref and out in method overloading

Both Ref and Out cannot be used in case of overloading.

// Compile time error as Below:
//Cannot define overloaded method 'Example1' because it differs from another method only on ref and out
private static void Example1(ref int iRef)
{
            
}

private static void Example1(out int iOut)
{
    iOut = 10; // iOut must be assigned
} 

However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.

static void Main(string[] args)
{
    int iOut=0; // May be initialize or may be not.
    Example1(out iOut);
    Console.WriteLine(iOut);
}

private static void Example1(int iRef)
{
            
}
private static void Example1(out int iOut)
{
    iOut = 10; // iOut must be assigned
}

Special notes

  • Both are treated same at compile time, but treated differently at runtime.
  • Properties could not be passed as an out or ref parameter



Folks you should also refer below articles for better understanding of differences between confusing concepts:



One comment

Leave a Reply