• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C# error CS0200 help.

PowerMacG5

Diamond Member
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?
 
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...
 
Back
Top