Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property or indexer 'string.this[int]' cannot be assigned to -- it's read only

Tags:

string

c#

I didn't get the problem - I was trying to do a simple action:

for(i = x.Length-1, j = 0 ; i >= 0 ; i--, j++)
{
    backx[j] = x[i];
}

Both are declared:

String x;
String backx;

What is the problem ? It says the error in the title... If there is a problem - is there another way to do that? The result (As the name 'backx' hints) is that backx will contain the string X backwards. P.S. x is not empty - it contains a substring from another string.

like image 676
user3220493 Avatar asked Feb 28 '14 11:02

user3220493


4 Answers

Strings are immutable: you can retrieve the character at a certain position, but you cannot change the character to a new one directly.

Instead you'll have to build a new string with the change. There are several ways to do this, but StringBuilder does the job in a similar fashion to what you already have:

StringBuilder sb = new StringBuilder(backx);
sb[j] = x[i];
backx = sb.ToString();

EDIT: If you take a look at the string public facing API, you'll see this indexer:

public char this[int index] { get; }

This shows that you can "get" a value, but because no "set" is available, you cannot assign values to that indexer.

EDITx2: If you're looking for a way to reverse a string, there are a few different ways, but here's one example with an explanation as to how it works: http://www.dotnetperls.com/reverse-string

like image 121
Chris Sinclair Avatar answered Oct 23 '22 03:10

Chris Sinclair


String is immutable in .NET - this is why you get the error.

You can get a reverse string with LINQ:

string x = "abcd";
string backx = new string(x.Reverse().ToArray()); 

Console.WriteLine(backx);    // output: "dcba"
like image 34
w.b Avatar answered Oct 23 '22 04:10

w.b


String are immuatable. You have convert to Char Array and then you would be able to modify. Or you can use StringBuilder.

for example

char[] wordArray = word.ToCharArray();
like image 21
jeevjyot singh chhabda Avatar answered Oct 23 '22 04:10

jeevjyot singh chhabda


In C# strings are immutable. You cannot "set" Xth character to whatever you want. If yo uwant to construct a new string, or be able to "edit" a string, use i.e. StringBuilder class.

like image 39
quetzalcoatl Avatar answered Oct 23 '22 05:10

quetzalcoatl