Ref And Out Keyword In C#

What is Ref and Out?

Ref
and out are basically C# Keywords. These keywords are used for calling function by reference. These keywords passes the reference of the variable to the function instead of the value.

For example: Let's swap two integer variables values:
  1. public static void Swap(int a, int b)  
  2. {  
  3.    int c = 0;  
  4.    c = a;  
  5.    a = b;  
  6.    b = c;  
  7.    Console.WriteLine("1) Values after swap a={0} b={1}",a,b);  
  8. }  
  9. static void Main(string[] args)  
  10. {  
  11.    int a = 5;  
  12.    int b = 6;  
  13.    Swap(a,b);  
  14.    Console.WriteLine("2) Values after swap a={0} b={1}", a, b);  
  15.    Console.ReadKey();  
  16.   
  17. }  
Here, we are swapping only the value but not swapping the value from actual address. If we want to swap value from memory location in C#, we need to use ref or out keyword.
 
For example
  1. public static void Swap(ref int a,ref int b)  
  2. {  
  3.    int c = 0;  
  4.    c = a;  
  5.    a = b;  
  6.    b = c;  
  7.    Console.WriteLine("1) Values after swap a={0} b={1}",a,b);  
  8. }  
  9. static void Main(string[] args)  
  10. {  
  11.    int a = 5;  
  12.    int b = 6;  
  13.    Swap(ref a,ref b);  
  14.    Console.WriteLine("2) Values after swap a={0} b={1}", a, b);  
  15.    Console.ReadKey();  
  16. }  
Here will be do actual swapping because we are passing address instead of value using ref keyword.  We can do thr same as out keyword but there are some difference between ref and out keyword. Let's see about the difference between ref and out
 
Difference between Ref and out keyword 
  1. Ref and out both used for passing parameter to a function.

  2. Ref keyword must be assigned a value before passing to the function whereas out keyword doesn't need to initialize before passing to the function.  
What we can not do with ref and out keyword? 
  1. Properties cannot be passed to ref or out parameters since internally they are functions not a member variable.

  2. Both Ref and Out cannot be used for method overloading simultaneously. Ref and Out treated differently at run time but actually they treated same at compile time.
For Example
  1. class MyClass  
  2. {  
  3.    public void Method(out int a) // compiler error “cannot define overloaded”  
  4.    {  
  5.       // method that differ only on ref and out"  
  6.    }  
  7.    public void Method(ref int a)  
  8.    {  
  9.       // method that differ only on ref and out"  
  10.    }  
  11. }  
Ebook Download
View all
Learn
View all