Curriculum
In C#, parameters in a function can be passed by value or by reference. When a parameter is passed by reference, the function receives a reference to the original variable, and any changes made to the parameter inside the function affect the original variable outside of the function. This is known as call by reference.
Here is an example of a function that takes two integers as parameters and swaps their values using call by reference:
public void Swap(ref int a, ref int b) { int temp = a; a = b; b = temp; }
When this function is called with the parameters a = 2
and b = 3
like this:
int x = 2; int y = 3; Swap(ref x, ref y);
the values of x
and y
are swapped, and x
now equals 3 and y
now equals 2.
In call by reference, the function can modify the original values of the variables passed as parameters. To pass a parameter by reference, you must use the ref
keyword when defining the parameter in both the function signature and the function call.