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?
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
}
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
}
Pass by Value
Pass by Reference