In C#, string is a reference type. Then,
Why do I need to have my swap function to have ref parameters?
swap(ref string first, ref string second) //swap(string first, string second) doesn't work
{
temp = first;
first = second
second = temp;
}
Yes,
stringis a reference type and thispasses references to the
stringobjects to the function.But
stringis immutable so it is not possible for the swap function to change the objects through these references. For strings, the only way to implement a swap function is to use the ref keyword to pass the references by reference so the references can be swapped.OTOH, if you have a mutable class, you can write a swap function without using the ref keyword:
But note, that after the swap, foo1Copy.Bar == 2, since the object referenced by foo1 and foo1Copy was modified.