When I try to assign to individual characters in a string with s[i] = c I get a compiler error:
string s = "bcc";
s[0] = 'a'; // shows compile time error - indexer cannot be assigned - it's readonly
However this works:
s.ToCharArray()[0] = 'a';
and we can also completely assign the string to acc:
s = "acc"
This:
… is changing the value of the variable to refer to a different string. If this were allowed:
that wouldn’t be changing the value of the variable – it would have to change the contents of the string that
sreferred to. Strings are immutable in .NET, so that’s not allowed.It’s important to differentiate between changing the value of a variable and changing the data within the object it refers to.
Changing the contents of
s.ToCharArray()doesn’t do anything to eithersor the string – it just mutates the newly-created array which is a copy of the data within the string.