PassbyValue vs PassbyReference


In this article we are going to discuss about Pass by Value and Pass by Reference with examples in C#.

What is the difference between Pass by Value and Pass by Reference Parameters?

  1. Pass by Value - When you pass parameters by value, a copy of the actual value is passed to the method. Changes made to the parameter inside the method do not affect the original value. In this example, the value of a remains 5 after the method call.

    public void Increment(int number)
    {
        number++;
    }
    
    static void Main()
    {
        int a = 5;
        Increment(a);
        Console.WriteLine(a); //Output:5
    }
  2. Pass by Reference - When you pass parameters by reference, a reference to the actual memory location of the parameter is passed. Changes made to the parameter inside the method affect the original value. In this example, the value of a is changed to 6 after the method call.

    public void Increment(ref int number)
    {
        number++;
    }
    
    static void Main()
    {
        int a = 5;
        Increment(ref a);
        Console.WriteLine(a); //Output:6
    }

Differences

  • Pass by Value

    • A copy of the value is passed.
    • Changes inside the method do not affect the original variable.
    • Memory allocation for the parameter is separate from the original variable.
  • Pass by Reference

    • A reference to the original variable is passed.
    • Changes inside the method affect the original variable.
    • Both the original variable and the method parameter point to the same memory location.

Prev Next