Hi I\'m trying to do a simple swap of two objects.My code is
void Main()
{
object First = 5;
object Second = 10;
Swap(First, Second);
//If I display res
There's various different things here:
First
and secondMain
Swap
now; the important thing is the difference between "reference type / references", and "pass by reference". They are completely unrelated.
in the line:
Swap(First, Second);
you pass the values of two variables to Swap
. In this case, the value of First
/ Second
is the reference to the boxed object.
Next;
private static void Swap(object First, object Second)
{
object temp = First;
First = Second;
Second = temp;
}
Here, you swap the value of two local parameters, but these are completely independent to anything else. If we want the caller to see the change to the values (i.e. reassignment), we need to pass by reference:
private static void Swap(ref object First, ref object Second)
{
object temp = First;
First = Second;
Second = temp;
}
Now the value of First
is no longer a reference to the boxed object; it is a reference to a reference to the boxed object. At the caller, we use:
Swap(ref First,ref Second);
which means pass the reference of variable First
, rather than pass the value of variable First
.
Note that I said you could forget about the fact that there is an object? Everything above is exactly the same if we used:
int x = 1, y = 2;
Swap(ref x, ref y);
void Swap(ref int a, ref int b) {
var tmp = a; a = b; b = tmp;
}
the only difference is that the value of x
is 1 etc, and ref x
is a reference to variable x. In pass by reference, reference-type vs value-type is completely irrelevant; the only important thing is understanding that you pass the value of a variable by default, where the value of a variable is 1
(etc), or "a reference to an object". Either way, the logic is the same.