This is passing parameters by Value. These value-type parameters in C# copy the actual parameters to the function (known as formal parameters) rather than referencing it.
Whenever a method is called by passing value, a new storage location is created for each value parameter. The copies of these values are stored, hence the changes made in the formal parameter have no effect on the actual argument.
Example: C# call by value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System; namespace Programs { class Swapping { //swapping function (user-defined) public void swapFunc(int x, int y) { int temp; temp = x; x = y; y = temp; } //main method static void Main(string[] args) { Swapping swapObj = new Swapping(); int a = 10, b = 20; Console.WriteLine("Before swapping, a: {0}", a); Console.WriteLine("Before swapping, b: {0}", b); //calling swap funciton by passing a and b swapObj.swapFunc(a, b); Console.WriteLine("\nAfter swapping, a: {0}", a); Console.WriteLine("After swapping, b: {0}", b); } } } |
Output:
1 2 3 4 5 | Before swapping, a: 10 Before swapping, b: 20 After swapping, a: 10 After swapping, b: 20 |
As you can see the value of a and b is not changed, even though the two value are swapped inside a function.