Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# assign char and char array to string?

        char character = 'c';
        string str = null;
        str = character.ToString();//this is ok

        char[] arrayChar = { 'a', 'b', 'c', 'd' };
        string str2 = null;
        str2 = string.Copy(arrayChar.ToString());//this is not ok
        str2 = arrayChar.ToString();//this is not ok.

I'm trying to converting char array to string, but the last two attempts don't work. Other source I found and they have to create new string type, but I don't know why. Can someone give me little explaination, thanks.

like image 894
Bopha Avatar asked Apr 12 '10 17:04

Bopha


2 Answers

You need to construct a new string.

Doing arrayChar.ToString() calls the "ToString" method for the char[] type, which is not overloaded to construct a string out the characters, but rather to construct a string that specifies that the type is an array of characters. This will not give you the behavior that you desire.

Constructing a new string, via str2 = new string(arrayChar);, however, will give you the behavior you desire.

The issue is that, in C# (unlike C++), a string is not the same as an array of characters. These are two distinctly different types (even though they can represent that same data). Strings can be enumerated as characters (String implements IEnumerable<Char>), but is not, as far as the CLR is concerned, the same type as characters. Doing a conversion requires code to convert between the two - and the string constructor provides this mechanism.

like image 50
Reed Copsey Avatar answered Sep 19 '22 21:09

Reed Copsey


new string(arrayChar);
like image 29
Andrey Avatar answered Sep 16 '22 21:09

Andrey