Sunday, December 8, 2013

Difference between ref and out keywords

What is the difference between out and ref in C#?
There is a big difference between ref and out parameters at the language level. Before you can pass a ref parameter, you must assign it to a value. This is for the purpose of definite assignment analysis. On the other hand, you don't need to assign an out parameter before passing it to a method. However, the out parameter in that method must assign the parameter before returning.
The following sample C# program uses both the ref and out parameter types,its enough for you to understand the actual difference between ref and out keywords:
using System;  
 class Program { 
  static void SetStringRef (ref string value)
   {  
   if (value == "cat") // Test parameter value 
   { 
    Console.WriteLine ("cat"); } value = "dog"; // Assign parameter to new value  
  }    
  static void SetStringOut (int number, out string value) 
   { 
    if (number == 1) // Check int parameter 
   { 
    value = "one"; // Assign out parameter 
   } 
  else 
  { 
  value = "other"; // Assign out parameter 
  }  
}  
static void Main() 
 {  
   string value1 = "cat"; // Assign string value 
   SetStringRef (ref value1); // Pass as reference parameter  
  Console.WriteLine (value1); // Write result    
  string value2; // Unassigned string 
  SetStringOut (1, out value2);// Pass as out parameter 
  Console.WriteLine (value2); // Write result  
}   
}
see out put:
 ref and out usage examples (program output)
cat
dog one

No comments: