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 results it displays as
//Value of First as 5 and Second as 10
}
private static void Swap(object First, object Second)
{
object temp = First;
First = Second;
Second = temp;
}
Since objects are reference type, its reference should be passed to method and it should swap.
why is it not happening?
There’s various different things here:
Firstand secondMainSwapnow; the important thing is the difference between “reference type / references”, and “pass by reference”. They are completely unrelated.
in the line:
you pass the values of two variables to
Swap. In this case, the value ofFirst/Secondis the reference to the boxed object.Next;
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:
Now the value of
Firstis no longer a reference to the boxed object; it is a reference to a reference to the boxed object. At the caller, we use:which means pass the reference of variable
First, rather than pass the value of variableFirst.Note that I said you could forget about the fact that there is an object? Everything above is exactly the same if we used:
the only difference is that the value of
xis 1 etc, andref xis 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 is1(etc), or “a reference to an object”. Either way, the logic is the same.