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?
Quite simply, because calling ToString() on a char array gives you
Try
You don’t get
Hello WorldAlso calling Array.Reverse to reverse strings is a bad idea, Tony and Jon mention it in their – now famous – Stack Overflow Presentation