writing to a strings index

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

I have this code:
string test = new string(' ', 2);
test[0] = 't';

and I'm getting a compiler error that string.this[int] is read only. Hmmm.
Why? I didn't declare it const or readonly?
 
strings in .Net are immutable - i.e. you cannot change their content once
created; depending on your intended usage, you could use substring /
replace/ regex functions to create a new string based on yours, or you could
call .ToCharArray(), change the array, and then create a new string from the
array (one of the ctors accepts char[]).

Marc
 
Steve,

Strings are treated as immutable. Once you create one, you can't change
the contents of it. You can use it as an input to create new strings.

In this case, you would have to create a new string, and concatenate
them together, like so:

test = (new String('t', 1)) + test.Substring(1);

Hope this helps.
 
Try the StringBuilder class


Marc Gravell said:
strings in .Net are immutable - i.e. you cannot change their content once
created; depending on your intended usage, you could use substring /
replace/ regex functions to create a new string based on yours, or you could
call .ToCharArray(), change the array, and then create a new string from the
array (one of the ctors accepts char[]).

Marc



Steve said:
I have this code:
string test = new string(' ', 2);
test[0] = 't';

and I'm getting a compiler error that string.this[int] is read only.
Hmmm.
Why? I didn't declare it const or readonly?
 
great, thanks for all the answers everyone! While I don't understant why
they implemented the string class like this, I'm sure there is a logical and
sound explanation. I have since used substring to accomplish what I need.

Thanks again!
 
Steve,

Mainly for performance reasons, as well as confusion... It just makes a
good number of things easier knowing it won't change.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Steve said:
great, thanks for all the answers everyone! While I don't understant why
they implemented the string class like this, I'm sure there is a logical
and
sound explanation. I have since used substring to accomplish what I need.

Thanks again!

Steve said:
I have this code:
string test = new string(' ', 2);
test[0] = 't';

and I'm getting a compiler error that string.this[int] is read only. Hmmm.
Why? I didn't declare it const or readonly?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top