Ref and Out Parameters in C#

Both of the Ref and Out parameters are used to pass arguments to a method. Ref and Out both indicate that the parameter is being passed by reference. Let us see these two parameters one by one with sample code for each.

Ref parameter: the Ref parameter needs to be initialized before passing it to a method. The Ref keyword passes the parameter as a reference. In the case the parameter value is changed it is also reflected in the method. Check the following syntax for the Ref parameter.

Syntax

  1. // It is necessary to initialize the Ref parameter before passing to a method.  
  2. int i = 10;  

  3. //Ref Parameter passed to the method.  
  4. Display(ref i);  
As stated previously, when a variable is declared it needs to be initialized, so in the preceding syntax we have declared and initialized the variable before passing it to a method.

Sample Code
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         int i = 10;  
  6.          
  7.         Display(ref i);  
  8.   
  9.         Console.ReadLine();  
  10.     }  
  11.   
  12.     public static void Display(ref int value)  
  13.     {  
  14.           Console.Write(value + 10);  
  15.     }  
  16. }  
Output



In the preceding example we have initialized the parameter to 10. And inside the Display method the ref parameter value is incremented with 10. If the ref parameter value is changed in the method that is being called then the parameter value is reflected in the calling method too.

Out Parameter: When passing a parameter to a method if there is no need to initialize the parameter then the Out parameter can be used. It is also passed as a reference. Since we do not initialize it before passing it to the method, it is necessary to initialize in the method in which it is being called before returning the value. Check the following syntax for the Out parameter.

Syntax
  1. // Variable is declared but there is no need to initialize.  
  2. int a;  
  3.   
  4. Display(out a);  
As we know there is no need to initialize the variable so we have just declared the variable. It will be initialized in the called method. Check the following code.

Sample Code
  1. class Program  
  2.  {  
  3.      static void Main(string[] args)  
  4.      {  
  5.          int a;  
  6.   
  7.          Display(out a);  
  8.   
  9.          Console.ReadLine();  
  10.   
  11.      }  
  12.   
  13.      public static void Display(out int x)  
  14.      {  
  15.          x = 10;  
  16.   
  17.          Console.Write(x);  
  18.      }  
  19.   
  20.  }  
Output

Up Next
    Ebook Download
    View all
    Learn
    View all