Search code examples
c#arraysstringnew-operatortostring

C# Return new string vs .ToString()


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 don't 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 that's just a guess).

What's 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?


Solution

  • Quite simply, because calling ToString() on a char array gives you

    System.Char[]

    Try

        char[] ca = "Hello world".ToCharArray();
        Console.WriteLine("{0}", ca);
    

    You don't get Hello World

    Also calling Array.Reverse to reverse strings is a bad idea, Tony and Jon mention it in their - now famous - Stack Overflow Presentation