ref vs out

In this post we’ll learn the difference between ref vs out. Both ref and out keywords in C# are used for passing arguments to methods by reference. This will allow changes to the argument within the method to affect the original variable. However, there are a few key differences between these two:

RefOut
When using the ref keyword, the variable needs to be initialized before it is passed. When using the out keyword, the variable does not have to be initialized before passing to the method. Only declaration of variable is enough.
It suggests that the method will read from and write to the variable.While using out the method must assign a value to the out parameter before the method returns. It suggests that the method is expected to output through this parameter.
When “ref” keyword data may pass in bi-directional.With “out” keyword data can only passed in unidirectional.

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.

Ref keyword Example:

class CodeConfig 
  {
    static public void Main()
    {
  
        // Declaring variable but not assigning value
          string name="test user";
        // Pass variable name to the method but using ref keyword
         UpdateName(out name);
  
      
       // Show the value of name in console
       Console.WriteLine("Name of student is:"+ name);
       //above will show Code config as output and this because of ref
     }
  
    //in below method passed int type "name" parameter but using ref keyword
    public static void UpdateName(ref string name)
    {
      //update name parm value to "Code config", it will update actual copy of "name" variable  
       name ="Code config";           
        
    }
}

Out keyword:

Out keyword passes also arguments by reference. While using it is quite similar to the ref keyword. The out parameter does not pass the property. It is generally used when our method returns multiple values instead of single value.

Out keyword Example:

class CodeConfig 
  {
    static public void Main()
    {
  
        // Declaring variable but not assigning value
           int G;
           string name;
        // Pass variable marks to the method but using out keyword
         Add(out marks, out name);
  
       // it is used best in case method returns multiple values as below  
       // Show the value of name & marks in console
       Console.WriteLine("Name of student is:"+ name);
       Console.WriteLine("Marks of student is:"+ marks);
    }
  
    //in below method passed int type "marks" parameter but using out keyword
    public static void Add(out int marks, out string name)
    {
       
       name ="Code config";           //Set name parm value 
       
        G = 10;                       //Set marks parm value   
        G = G +G;
    }
}

You can check more .Net interview questions and answers HERE.