Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return new string vs .ToString()

Tags:

arrays

string

c#

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?

like image 231
Leroy Jenkins Avatar asked Apr 06 '10 14:04

Leroy Jenkins


3 Answers

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

like image 152
Binary Worrier Avatar answered Oct 17 '22 07:10

Binary Worrier


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.

like image 22
flq Avatar answered Oct 17 '22 07:10

flq


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         
like image 25
cjk Avatar answered Oct 17 '22 08:10

cjk