C# error CS0200 help.

PowerMacG5

Diamond Member
Apr 14, 2002
7,701
0
0
I am trying to manipulate a string within C#, and I keep getting this error:

error CS0200: Property or indexer 'string.this[int]' cannot be assigned to -- it is read only

Here is the code snippet that is causing this:
string x = "Hello";
x[0] = 'a';

Shoudln't this work as it does in C++, giving the new value of aello to x? If not, what is the proper way of doing this?
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
In .NET, a System.String is truly immutable. In other words, you can't alter it... at all. Any operation on an immutable string results in the creation of a new string. This is a fairly expensive operation. If you look at the Chars property (the indexer) of System.String you'll notice there is a get operation, but not a set operation. In order to edit a String in the manner you're describing, you'll need to use a System.Text.StringBuilder. e.g.:

StringBuilder x = new StringBuilder();
x.Append("Hello");
x[0] = 'a';

If you're familiar with .NET you'll probably ask yourself, "Why is the indexer for String/StringBuilder Chars instead of the default Item?" Well, if you create an indexer it will, by default, emit the Items property of the same type your indexer returns. You can apply the IndexerNameAttribute to the indexer to override this. This is how they got it to be Chars...