Friday, December 02, 2011

Parameters: Call “by value” and “by reference”

When a parameter is send to a method as by value, the argument receiving the parameter will have copy of its value. When we change the argument variable within the method, it will not be reflected in the original parameter.

When a parameter is send to a method as by reference, the argument receiving the parameter will have the reference to the parameter. In effect, When we change the argument variable within the method, it will be reflected in the original parameter.

class Program
{
    static void Main(string[] args)
    {
        int v = 10;

        Console.WriteLine("Call by Value:");
        Console.WriteLine("Before Call:");
        Console.WriteLine("  v: " + v.ToString());

        SetDataByValue(v);

        Console.WriteLine("After Call:");
        Console.WriteLine("  v: " + v.ToString());

 

        Console.WriteLine();
        v = 10;
        Console.WriteLine("Call by Reference:");
        Console.WriteLine("Before Call:");
        Console.WriteLine("  v: " + v.ToString());

        SetDataByRef(ref v);

        Console.WriteLine("After Call:");
        Console.WriteLine("  v: " + v.ToString());
       
        Console.ReadKey();
    }

    static void SetDataByValue(int a)
    {
        a = a + 1;
    }

    static void SetDataByRef(ref int a)
    {
        a = a + 1;
    }
}

Output

Call by Value:
Before Call:
  v: 10
After Call:
  v: 10

 

Call by Reference:
Before Call:
  v: 10
After Call:
  v: 11

No comments:

Post a Comment