Pass By Value and Pass By Reference In C#
Pass By Value:
By default, the method parameters are passed by value. That is a parameter declared with no modifier is passed by value is called Value Parameter. When a method is invoked, the values of actual parameters are assigned to the corresponding formal parameters. The values of the value parameters can be changed within the method.
Example:
using System; class PassValue { static void Change(int k) { k=k+10; } public static void Main() { int i=50; Change(i); Console.WriteLine("i =" +i); } }
Output:
i = 50
Pass By Reference:
In C#, the value parameters to be passed by reference. To do this, we use the ref keyword. It has the following syntax:
void Modify(ref int x) // x is declared as a reference parameter.
Example:
using System; class PassReference { static void Swap(ref int p, ref int q) { int temp=p; p=q; q=temp; } public static void Main() { int x=50, y=60; Console.WriteLine("Before Swapping"); Console.WriteLine("x= " +x); Console.WriteLine("y= " +y); Swap(ref x, ref n); Console.WriteLine("After Swapping"); Console.WriteLine("x= " +x); Console.WriteLine("y= " +y); } }
Output:
Before Swapping
x=50
y=60
After Swapping
x=60
y=50