return new string vs .ToString()

Posted by Leroy Jenkins on Stack Overflow See other posts from Stack Overflow or by Leroy Jenkins
Published on 2010-04-06T14:55:00Z Indexed on 2010/04/06 15:03 UTC
Read the original article Hit count: 355

Filed under:
|
|
|

Take the following code:

    public static string ReverseIt(string myString)
    {
        char[] foo = myString.ToCharArray();
        Array.Reverse(foo);
        return new string(foo);
    }

I understand that strings are immutable, but what I dont understand is why a new string needs to be called

return new string(foo);

instead of

return foo.ToString();

I have to assume it has something to do with reassembling the CharArray (but thats just a guess).

Whats the difference between the two and how do you know when to return a new string as opposed to returning a System.String that represents the current object?

© Stack Overflow or respective owner

Related posts about c#

Related posts about string