Difference Between Ref and Out parameters

The Ref and Out parameter is used when your method wants to return one or more values.

Ref Keyword

While using the Ref keyword we need to initialize the parameter before passing to method. If you want to pass variable as Ref parameter you need to initialize before pass. Ref keyword will pass parameter as reference, it means when the value of parameter is changed in called method it get reflected in calling method.

Example:

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         int intRef = 2;  
  6.         int Value = MethodCall(ref intRef);  
  7.         Console.WriteLine("Ref Value : " + Value);  
  8.         Console.ReadLine();  
  9.     }  
  10.   
  11.     private static int MethodCall(ref int intRef)  
  12.     {  
  13.         return 5 + intRef;  
  14.     }  
  15.   
  16. }   
Output:

Ref Value : 7

Out Keyword

While using Out keyword we don’t need to initialize the parameter before passing to method. Out keyword also you pass as parameter as reference but here we need to initialize out parameter before it return to calling method.

Example:
  1. static void Main(string[] args)  
  2. {  
  3.     int intOut;  
  4.     int Value = MethodCall(out intOut);  
  5.     Console.WriteLine("Out Value : " + Value);  
  6.     Console.ReadLine();  
  7. }  
  8.   
  9. private static int MethodCall(out int intOut)  
  10. {  
  11.     return intOut = 3;  
  12. }  
Output:

Out Value : 3

Note:

  1. Passing by reference and the concept of reference type these two concepts are not the same.
  2. Properties cannot be passed to ref or out parameters since internally they are functions.
Ebook Download
View all
Learn
View all