Here reference refers t the addresses but not the actual value. In this method, we pass the reference of the argument to the formal parameter. To pass the parameters in C#, we have a keyword called ref
.
It passes a reference to a memory location rather the actual value, so the changes made to this passed parameters are reflected o the main program that is their value can be modified permanently.
Example: C# call by reference
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(ref int x, ref 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 with ref keyword swapObj.swapFunc(ref a, ref 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: 20 After swapping, b: 10 |
Unlike call by value (from the previous tutorial), the swapped value of a and b can be seen in the output above.