Tuesday, 16 October 2012

What is the difference between the out and ref parameter modifiers?

Both the out and ref modifiers can be applied to method arguments. And, both imply that the argument will be passed by reference—either as a reference to a value type variable or to a reference type variable. However, the out parameter enables passing in an uninitialized variable and guarantees that it will come back with set to a value.

int integer;
AccessByReference (out integer)
 
 // on return, integer has been set to an int value 
 



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:
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
   }
 
}


 ref and out usage examples (program output)
cat dog one

No comments :