Jump to content
  • Advertisement
Sign in to follow this  
Eriond

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

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

If you intended to correct an error in the post then please contact us.

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 this post


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

Cheers

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by Talonius
char 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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!