A ref
parameter means that the method (Swap
in this case) can re-point your P1
and P2
references to other objects. It would cause issues if the compiler let you assign objects of types that are incompatible with Person
to those variables.
For example if you had a Car
class you wouldn't want the compiler to let you assign that to your P1
and P2
references just on the basis that it's derived from Object
because it's not derived from Person
at all, and as such isn't guarantied to share the same methods, fields & properties, meaning a Car
object probably won't be interchangeable with a Person
object.
You could however infer the type based on your usage with Generics:
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/generics
static void Swap<T>(ref T O1, ref T O2)
{
T O = O1;
O1 = O2;
O2 = O;
}
Here the compiler can work out that you're passing in a Person
and it'll insert that into this dynamic T
argument, ensuring that O1
and O2
are the same type, and also that T
is the same as the types of the variables you're ref
ing them in to.