i have a code in c# like below
string s = new string('~',25);
int ind = 5;
s[ind] = 'A';
it gives an error
Property or indexer ‘string.this[int]’ cannot be assigned to — it is read
so what is the problem, and how can i fix it.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Strings are immutable – you can’t change an existing one.
Two options:
Use
StringBuilder, e.g.Build a new string from a char array:
In both cases you could populate the mutable data without building a new string to start with if you want – that would involve more code, but would probably be more efficient.
Alternatively, you can take substrings and concatenate them together, as per another answer …there are basically lots of ways of tackling this. Which one is appropriate will depend on your actual use case.