Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.String underlying implementation

Tags:

string

c#

.net

I was recently trying to do the following in c#

string str = "u r awesome";
str[0]="i";

And it wouldn't work because apparently str[i] is only a get not a set, so I was wondering what the underlying implementation of string is that would force str[i] to only be a get.

Isn't it just a managed wrapper for a char *? So then why can't I set str[i]?

like image 454
etk1220 Avatar asked Aug 09 '11 01:08

etk1220


2 Answers

You can't set characters of a string because the .NET String class is immutable -- that means that its contents cannot be changed after it is created. This allows the same string instance to be used many times safely, without one object worrying that another object is going to stomp on its strings.

If you need a mutable class that lets you manipulate a string of characters, consider using StringBuilder instead.

If you want to compare to C, the String type is like const char * except that you cannot just cast away the constness. StringBuilder is more like a char * (with automatic allocation resizing) and with a method (ToString()) to create a new, independent String instance from its contents.

like image 85
cdhowie Avatar answered Oct 04 '22 20:10

cdhowie


The answers the others gave concerning immutability are of course correct and are the "actual" cause of the issue your having.

Since you specifically asked about the underlying implementation (and if just out of curiosity), and as a reference to others that might stumble upon this question, here is some more information about that topic from Eric Lippert:

"In the .NET CLR, strings are laid out in memory pretty much the same way that BSTRs were implemented in OLE Automation: as a word-aligned memory buffer consisting of a four-byte integer giving the length of the string, followed by the characters of the string in two-byte chunks of UTF-16 data, followed by two zero bytes."

Note the "pretty much" part here, however BSTR themselves are also explained in Eric's blog.

Mind you, that all of this should be considered an implementation detail. And even though it shouldn't really concern most of us, it might help though during debugging interop issues or in general understanding.

like image 37
Christian.K Avatar answered Oct 04 '22 20:10

Christian.K