Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Passing parameters by value and reference in CSharp

Generic Interface:

In CSharp there are 3 ways a parameter can be passed into a method:

  • By value: It's the default way.
  • By reference In: The variable value is set before the method is called.
  • By reference Out: The variable value will be set by the method.

The behaviour of the parameters will change depending on whether references types or values types.

class PassingValByVal
{
    // The parameter x is passed by value. 
    // Changes to x will not affect the original value of x.
    static void SquareIt(int x)
    {
        x *= x;
        Console.WriteLine("Value inside: {0}", x);
    }

    static void Main()
    {
        int n = 5;
        Console.WriteLine("Value before: {0}", n);

        SquareIt(n);  // Passing by value.
        Console.WriteLine("Value after: {0}", n);
    }
}

/*  
    Value before: 5
    Value inside: 25
    Value after:  5
*/

class PassingValByRef
{
    // The parameter x is passed by reference. 
    // Changes to x will affect the original value of x.
    static void SquareIt(ref int x)
    {
        x *= x;
        Console.WriteLine("The value inside the method: {0}", x);
    }

    static void Main()
    {
        int n = 5;
        Console.WriteLine("Value before: {0}", n);

        SquareIt(ref n);  // Passing by reference.
        Console.WriteLine("Value after: {0}", n);
    }
}

/*  
    Value before: 5
    Value inside: 25
    Value after:  25
*/

No Comments