Ref And Out Parameters In C#

Though both ref and out parameters are used to pass the parameters by reference, they aren’t used in exactly the same way.

Ref

Ref keywords are used to pass an argument as a reference, meaning that when the value of that parameter changes in the called method, the new value is reflected in the calling method. An argument passed using the ref keyword must be defined in the calling method before getting passed to the called method.

Out

Out keywords is similar to ref keywords but they are different because the arguments passed using out keywords can be passed without any value to be assigned to it. An argument passed using the out keyword must be defined in the called method before being returning to the calling method.
  1. public class Test {  
  2.     public static void Main() //calling method  
  3.     {  
  4.         int parameter1 = 1; 
  5.         int parameter2; // initialization optional.

  6.         Function1(ref parameter1); // Passed parameter using ref  
  7.         Console.WriteLine(parameter1); // parameter1=2
  8. -
  9.         Function2(out parameter2); // Passed parameter using out  
  10.         Console.WriteLine(parameter2); // parameter2=5  
  11.     }  

  12.     static void Function1(ref int value) //called method
  13. // so we can get parameter1's value here so so it will change parameter1 value to 1 after this method get called.
  14.     {  
  15.         value++;  //here we get 0 in value so value++ we get 2.
  16.     }  

  17.     static void Function2(out int value) 
  18. /*we can not get parameter2 value here, we have to initialize value to variable before returning from this method.*/
  19.     {  
  20.         value = 5; //must be defined  
  21.     }  
  22. }  
  23. /* Output 
  24. 2
  25. 5 
  26. */  
Ebook Download
View all
Learn
View all