Working With Ref And Out Parameter In C#

Here we discuss the ref and out parameters in C#. They are basically parameters and we can use it in a different way.
 

ref parameter

 
It is used as a call by reference in C#. It is used both places; when we declare a method and when we call the method. The following example will explain how we use the ref parameter in C#. In this example we create a function (cube) and pass a ref parameter in it, now we look at the value before we call the function and after we call the function,
  1. class TryRef  
  2. {  
  3.     public void cube(ref int x)  
  4.     {  
  5.         x= x * x * x;     
  6.     }  
  7. }  
  8. class Program  
  9. {  
  10.     static void Main(string[] args)  
  11. {  
  12.     TryRef tr = new TryRef();  
  13.     int y = 5;  
  14.     Console.WriteLine("The value of y before   
  15. the function call: " + y);  
  16.     tr.cube(ref y);  
  17.     Console.WriteLine("The value of y after the function call: " + y);  
  18.         Console.ReadLine();  
  19.     }  
  20. }  
The output will be,
 
Working With Ref And Out Parameter In C#
 
Now we take multiple ref parameters in our next program,
  1. class tryref  
  2. {  
  3.     public void mul(ref int i, ref int j)  
  4.     {  
  5.         j = i * j;  
  6.     }  
  7. }  
  8. class Program  
  9. {  
  10.     static void Main(string[] args)  
  11.     {  
  12.         tryref tf = new tryref();  
  13.         int i = 5;  
  14.         int j = 10;  
  15.         Console.WriteLine("The value of i and j before the call :"+i+","+j);  
  16.             tf.mul(ref i, ref j);  
  17.             Console.WriteLine("The value of i and j after the call :" + i + "," + j);  
  18.         Console.ReadLine();  
  19.     }  
  20. }  
The output will be,
 
Working With Ref And Out Parameter In C#
 

Out parameter

 
Sometimes we do not want to give an initial value to the parameter; in this case we use the out parameter. The declaration of the out parameter is the same as the ref parameter. But it is used to pass the value out of a method. Now we look at the example,
  1. class tryout  
  2. {  
  3.     public int mul(int a, out int b)  
  4.     {  
  5.         b = a * a;  
  6.         return b;  
  7.     }  
  8. }  
  9. class Program  
  10. {  
  11.     static void Main(string[] args)  
  12.     {  
  13.         tryout to = new tryout();  
  14.         int x,y;  
  15.   
  16.         x = to.mul(10, out y);  
  17.         Console.WriteLine("The output is: "+x);  
  18.         Console.ReadLine();  
  19.    
  20.    
  21.     }  
  22. }  
The Output will be,
 
Working With Ref And Out Parameter In C#