views:

382

answers:

3
        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.

+5  A: 
new string(arrayChar);
Andrey
mind to explain why have to create new string?
Bopha
Isn't that what you want to do?
Matti Virkkunen
@Bopha: I tried to explain this in my answer for you - does that help? @Andrey: +1 for being the correct answer, too :)
Reed Copsey
yep that is what I want to do, but wonder why I have to create new string to set array char to string. Because I thought string is just a sequence of character representing like array. The reason of that because I can access individual character in string by applying the bracket and index position.
Bopha
@Bopha - because char[] is mutable and string is not. this is the way strings are designed and implemented in .net
Andrey
@Bopha - you can use [] with string with same results.
Andrey
@Bopha: In .NET, strings are immutable, which means you can't "set" anything to an existing string. The only way is to create a new string.
Matti Virkkunen
ohh I see. Awsome! thanks for the explainations.
Bopha
A: 

There is a string constructor that takes a char array.

Brian R. Bondy
+8  A: 

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.

Reed Copsey
now that is the answer i'm looking for. thank you Reed.
Bopha