Sunday, August 30, 2020

Difference between ref and out parameters in C#

 Ref and out keywords in c# are used to pass arguments within a method or function. Both indicate that an argument passed by reference. By default parameter are passed to a method by value. By using these keywords we can pass a parameter by reference.

Ref –

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

Example : Ref  Keyword – C#

 
 public static string GetNextName(ref int id)  
  {  
    string returnText = "Next-" + id.ToString();  
    id += 1;  
    return returnText;  
  }  
 static void Main(string[] args)  
  {  
    int val = 1;  
    Console.WriteLine("Previous value of integer val:" + val.ToString());  
    string test = GetNextName(ref val);  
    Console.WriteLine("Current value of integer val:" + val.ToString());  
  } 
 

 

Output -

Previous value of integer val : 1

Current value of integer val : 2

 

Out –

The out keyword is used to pass arguments to method as a reference type and is primary used when a method has to return multiple values.

Example : Out  Keyword – C#

 
 public static string GetNextNameByOut(out int id)  
  {  
    id = 1;  
    string returnText = "Next-" + id.ToString();  
    return returnText;   
  }  
 static void Main(string[] args)  
  {  
    int val = 0;  
    Console.WriteLine("Previous value of integer val:" + val.ToString());  
    string test = GetNextNameByOut(out val);  
    Console.WriteLine("Current value of integer val:" + val.ToString());  
  } 
 

Output -

Previous value of integer val : 0

Current value of integer val : 1


Ref Vs Out

Ref Keyword            

Out Keyword

When ref keyword is used the data may pass in bi-directional.

When out keyword is used the data only passed in unidirectional.

In called method, It is not required to initialize the parameter passed as ref.

In called method, It is required to initialize the parameter passed as out.

Ref should not be used to return multiple values from method.

Out should be used to return multiple values from method.

Ref is useful when we already know the parameter value and called method can only modify the data.

Out is useful when we don't know the parameter value before calling the method.


No comments:

Post a Comment