ASP.NET MVC C#.NET Programming

Difference Between Ref Vs Out in C#.NET

Difference Between Ref Vs Out in C#.NET

Many time in the interview develops are confused in ref and out in C#.NET. So for more understanding lets take an example with proper explanation.

Ref Keyword

The ref keyword passes arguments by reference. It means any changes made to this argument in the method will be reflected in that variable when control returns to the calling method.

public static void Main() 
    { 
        string str = "avtartime";  // Assign string value 

        SetValue(ref str);  // Pass as a reference parameter
  
        Console.WriteLine(str); // Display the given string
    } 
  
    static void SetValue(ref string stringValue) 
    {         
        if (stringValue == "avtartime")   // Check parameter value
        { 
            Console.WriteLine("Welcome to AvtarTime"); 
        }   
    stringValue = "Hi Avtar";  // Assign the new value of the parameter 
    }

Output:
Welcome to AvtarTime
Hi Avtar

Out Keyword

 The out keyword passes arguments by reference. This is very similar to the ref keyword. 

static public void Main() 
    { 
        int a; // Declaring variable without assigning value

        Sum(out a); // Pass variable a to the method using out keyword
  
        // Display the value a 
        Console.WriteLine("The sum of" + " the value is: {0}",a); 
    } 

    // Method in which out parameter is passed 
    // and this method returns the value of 
    // the passed parameter 
    public static void Sum(out int a) 
    { 
        a = 50; 
        a += a; 
    } 

Output:
The sum of the value is: 100
REF OUT
It is compulsory the parameters should be initialized before it passes to ref. It is not necessary to initialize parameters before it pass to out.
The passing of value through ref parameter is useful when the called method also needs to change the value of the passed parameter. The declaring of parameter through out parameter is useful when a method return multiple values.
When ref is used the data may pass in bi-directional. When out is used the data only passed in unidirectional.
Also Read  CRUD operations in ASP.Net Web Forms using C#

About the author

Avtar

I am a blogger and I always believes in sharing a knowledge and happiness because happiness is the last journey of life.

Leave a Comment

Share
Tweet
Pin
+1
Share
0 Shares