Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting System.char[] printed out in this case?

I'm trying to figure out what I'm doing wrong here, but I can't seem to. I have this method that takes in a string and reverses it. However, when I print out the reversed string from the caller method, I just get "System.Char []" instead of the actual reversed string.

    static string reverseString(string toReverse)
    {
        char[] reversedString = toReverse.ToCharArray();
        Array.Reverse(reversedString);
        return reversedString.ToString();
    }
like image 620
Waffles Avatar asked Aug 25 '10 00:08

Waffles


2 Answers

Calling ToString on a T array in .NET will always return "T[]". You want to use this instead: new string(reversedString).

like image 132
bcat Avatar answered Oct 19 '22 16:10

bcat


By calling ToString you just get the default implementation that every class inherits from object. .NET can't provide a special implementation just for an array of char; the override would have to apply to all types of array.

Instead, you can pass the array to String's constructor, return new String(reversedString).

like image 34
stevemegson Avatar answered Oct 19 '22 16:10

stevemegson