Task
Write a procedure that swaps the values of two variables.
The peculiarity of this task is that we need the changes made in the procedure to become known to the calling program.
Let's try to write the procedure like this:
static void Swap (int a, int b) // with such a description of the procedure parameters,
{ // will copy the values of the arguments (x and y)
int c; // variables a and b are independent variables not related to x and y
c = a; a = b; b=c;
}
static void Main()
{
int x=1, y=2;
Swap(x, y); //values of variables x and y (arguments) are copied into parameters a and b, x = 1, y = 2
}
If you run this program, you can see that the values of the x and y variables have not changed. In order for the parameters to change the values of the arguments, you must use data passing by reference. To do this, you must write ref
before the name of the data type in the header of the subroutine.
void Swap ( ref int a, ref int b ) // now variables a and b get addresses of variables x and y in memory
{
int c;
c = a; a = b; b=c;
}
static void Main()
{
int x=1, y=2;
Swap(ref x, ref y);
Application: if you pass an argument by reference, then only the name of the variable (NOT a number and NOT an arithmetic expression) can stand in this place when calling the procedure.
You can't call a procedure like this:
Swap(x, 4);
Swap(5+x, y);