• 12
• 12
• 9
• 10
• 13

[.net] [C#]Why can't you assign a char[] to a string

This topic is 4893 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

char[] c = /* some string */;
string s = c; // doesn't work
// have to do
string s2 = new string(c);


Is there any reason no conversion exists?

Share on other sites
There's no implicit conversion; that's all.
Most of the time I use a StringBuffer to add characters.

Cheers

Share on other sites
I know it didn't work because there was no implicit conversion, I wondered about the reason it didn't exist :)

Share on other sites
There probably isn't an implicit conversion because that would imply that the process is trivial (most implicit conversions are reletively non-intensive). But since strings are immutable and char arrays aren't, the data from the array must be copied into a newly allocated buffer for the string, which isn't nearly as trivial as converting an int to a long for example. Just my take on it, but it seems to make sense.

Share on other sites
The CLR performs additional optimizations with strings that are not possible with arrays.
One example is the internal string pool used to conserve memory by not keeping duplicates. Take a look at the Intern method of string for more information.
There are probaly alot of other things that it does too. It may for instance perform compression or have methods of search/compare optimization.

Share on other sites
There is no implicit conversion as such, but there is a constructor that takes char[]

Share on other sites
I used that constructor in the code in my first post.

Share on other sites
I'd be more surprised if there was such a conversion.

Share on other sites
char is a value type. string is a reference type, albeit a specially treated one. Converting between them involves boxing the char array as a string. I can't think of any conversion that requires boxing that is done without explicit casting.

Share on other sites
Quote:
 Original post by Taloniuschar is a value type.

An array of char is a reference type. All arrays are reference types.
Quote:
 string is a reference type, albeit a specially treated one.

Specially treated how? String interning? The fact that you can have string literals?
Quote:
 Converting between them involves boxing the char array as a string.

Since the char array is a reference type, there would be no boxing.