Search This Blog

Monday, June 25, 2012

ref c#

C# Keywords > ref

The ref method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method.


using System;
public class MyClass
{
   public static void Ref(ref char x)
   {
      // The value of i will be changed in the calling method
      x = 'a';
   }
   public static void NoRef(char x)
   {
      // The value of i will be unchanged in the calling method
     x = 'b';
   }
   public static void Main()
   {
      char i = '';    // variable must be initialized
      Ref(ref i);  // the arg must be passed as ref
      Console.WriteLine(i);
      NoRef(i);
      Console.WriteLine(i);
   }
}