Professional Documents
Culture Documents
swapping Using Ref //swap - CS: Using Namespace Class Public Int Public Int Public Int Int
swapping Using Ref //swap - CS: Using Namespace Class Public Int Public Int Public Int Int
swapping Using Ref //swap - CS: Using Namespace Class Public Int Public Int Public Int Int
Let's come from the beginning, we know that there are four kinds of formal
parameters in a C# method declaration, namely
If so, then, if we pass two objects to a regular swap method and come back
to the calling procedure to see whether they have got swapped, they would
have not! Look down the code below,
In the above program, we pass the instances obj1 and obj2 of class1 to
badswap_noref() method and see that they are not actually getting
swapped. This is what actually happens in the badswap_noref method. Not
the actual references obj1 and obj2 are passed. But a copy of the references
is passed. So param1 and param2 contains a copy of the actual references
obj1 and obj2 respectively. We are able to modify the values of X and Y in
the badswap_noref method thru param1 and param2, because param1 and
param2 still points to the same address locations referred to by obj1 and
obj2. But what we are swapping is only param1 and param2, the method
references, which are not retained when we come back to the calling
procedure, Main().
Thus, in C#, a swap method can be made possible by using the ref keyword.
In such a case, we pass the object references explicitly by reference and not
by value, thus able to swap them right in the called method.