CSharp - Passing by value


By default, arguments in C# are passed by value.

A copy of the value is created when passed to the method:


using System;

class Program//from   ww  w. j a  v  a2  s  .c om
    static void Test(int p)
        p = p + 1;                // Increment p by 1
        Console.WriteLine(p);    // Write p to screen

    public static void Main(string[] args)
        int x = 8;
        Test(x);                  // Make a copy of x
        Console.WriteLine(x);    // x will still be 8


Assigning p a new value does not change the contents of x, since p and x reside in different memory locations.