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.
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.
new string(arrayChar);
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