Search code examples
c#.netstringvalue-typereference-type

Why do I need to pass strings by reference to my swap function?


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;
}

Solution

  • Yes, string is a reference type and this

    void swap(string first, string second)
    

    passes references to the string objects to the function. But string is 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:

    class Foo
    {
        public int Bar { get; set; }
    }
    
    static void Swap(Foo first, Foo second)
    {
        var temp = first.Bar;
        first.Bar = second.Bar;
        second.Bar = temp;
    }
    
    Foo foo1 = new Foo { Bar = 1 };
    Foo foo1Copy = foo1;
    Foo foo2 = new Foo { Bar = 2 };
    Swap(foo1, foo2);
    

    But note, that after the swap, foo1Copy.Bar == 2, since the object referenced by foo1 and foo1Copy was modified.