Monday, July 9, 2012

' ref ' keyword - Passing value types by reference

The ref method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method.  In other words if you do a certain changed to the parameter in the method it'l affect the originally passed arguement as well. To use a ref parameter, the argument must explicitly be passed to the method as a ref argument. 
The following example will explain the above mentioned facts.

 private static void TestMethod(ref int a)
{
    // at this point the original value will be modified 
    a = a * a;
}
static void Main(string[] args)
{
    int a = 10; // First 'a ' is initialized to 10
    TestMethod (ref a); // Invoking and passing ref arguement
    Console.WriteLine(a);
    Console.ReadLine();
    // Output a = 100;
    // If it was not passed by reference the output would be 10      
}

2 comments:

  1. Pass by reference. The place where we used "&",between the data type and the identifier, inside the parameter to represent it in C++.

    :)

    ReplyDelete