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?
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
The second just calls ToString on an instance of char array, while the first uses a string constructor to obtain a string from a char array. They really have nothing to do with each other.
Here is the IL for the 2 functions:
private string test(String myString){
        char[] foo = myString.ToCharArray(); 
        Array.Reverse(foo); 
        return new string(foo); 
}
test:
IL_0000:  nop         
IL_0001:  ldarg.1     
IL_0002:  callvirt    System.String.ToCharArray
IL_0007:  stloc.0     
IL_0008:  ldloc.0     
IL_0009:  call        System.Array.Reverse
IL_000E:  nop         
IL_000F:  ldloc.0     
IL_0010:  newobj      System.String..ctor
IL_0015:  stloc.1     
IL_0016:  br.s        IL_0018
IL_0018:  ldloc.1     
IL_0019:  ret         
private string tess(String myString)
{
        char[] foo = myString.ToCharArray(); 
        Array.Reverse(foo); 
        return foo.ToString(); 
}
tess:
IL_0000:  nop         
IL_0001:  ldarg.1     
IL_0002:  callvirt    System.String.ToCharArray
IL_0007:  stloc.0     
IL_0008:  ldloc.0     
IL_0009:  call        System.Array.Reverse
IL_000E:  nop         
IL_000F:  ldloc.0     
IL_0010:  callvirt    System.Object.ToString
IL_0015:  stloc.1     
IL_0016:  br.s        IL_0018
IL_0018:  ldloc.1     
IL_0019:  ret         
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With