Monday, 11 July 2011

Difference between Ref and Out Parameter in C#

When we pass a parameter as ref to a method, the method refers to the same variable and changes made will affect the actual variable. Even the variable passed as out parameter is similar to ref, but there are few implementation differences when you use it in C#.
Argument passed as ref must be initialized before it is passed to the method, where as in case of out it is not necessary, but after a call to the method as an out parameter the variable must be initialized.
When to use ref and out parameter? out parameter can be used when we want to return more than one value from a method.

The out Parameter
The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.
public class mathClass
{
          public static int TestOut(out int iVal1, out int iVal2)
          {
                   iVal1 = 10;
                   iVal2 = 20;
                    return 0;
          }
          public static void Main()
          {
                   int i, j; // variable need not be initialized
                   Console.WriteLine(TestOut(out i, out j));
                   Console.WriteLine(i);
                   Console.WriteLine(j);
          }
}

The ref parameter
The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.
You can even use ref for more than one method parameters.
namespace TestRefP
{
          public class myClass
          {
                   public static void RefTest(ref int iVal1 )
                   {
                             iVal1 += 2;
                   }
                   public static void Main()
                   {
                             int i; // variable need to be initialized
                             i = 3;
                             RefTest(ref i );
                             Console.WriteLine(i);
                   }
          }
}

4 comments: