-1

I'm trying to assign "tela[counter] = letra.ToString();", but it shows up the following error message "Property or indexer 'string.this[int] cannot be assigned to -- it is read only".

I saw some topics saying that you have to define {get;set;} to the atribute, but I've done this, and it didn't work.

[OBS] I tried to create get and set methods but the problem persisted

     public String tela { get; set; }

    private void btnSendWord_Click(object sender, EventArgs e)
    {
        char letra = Convert.ToChar(txtGetWord.Text);
        MessageBox.Show(comboPalavra[0]);
        Boolean codigoVerificador;
        codigoVerificador =  verificador.VerificaLetra(comboPalavra[0],letra);
        if (codigoVerificador == true)
        {

            foreach(char c in comboPalavra[0].ToCharArray())
            {
                counter++;
                if(c == letra)
                {
                    tela[counter] = letra.ToString();
                }
            }
        }
        else MessageBox.Show("Nao contem");
    }
dev-john
  • 129
  • 9
  • 1
    You can't change content of the string with indexer. Create a new string rather (with StringBuilder for example) – Aleks Andreev Oct 01 '17 at 14:32
  • 3
    There's several things wrong with this. I suggest picking up a book on C# and reading it. Guessing is not considered good coding practice. – glennsl Oct 01 '17 at 14:34
  • [https://stackoverflow.com/questions/22093976/property-or-indexer-string-thisint-cannot-be-assigned-to-its-read-only](https://stackoverflow.com/questions/22093976/property-or-indexer-string-thisint-cannot-be-assigned-to-its-read-only) This should help.. – Stacking For Heap Oct 01 '17 at 14:35

2 Answers2

3

Strings are immutable, meaning that you can't change a variable's value without creating a new string.

You are trying to change a single character in a string here, which is not allowed:

tela[counter] = letra.ToString();

A solution to this is to use StringBuilder. You can think of it as a mutable version of string.

You can declare a StringBuilder outside the loop:

var telaBuilder = new StringBuilder(tela);

In the loop, change the erroneous line to:

telaBuilder[counter] = letra;

And after the loop, assign telaBuilder to tela:

tela = telaBuilder.ToString();

Don't forget using System.Text!

Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

This is the signature of the indexer for a string:

public char this[int index] { get; }

See that it returns a char and only has a get, that means it is readonly and you cannot assign something to it. This is why you are getting the error.

If you want to replace a specific letter in a string at a specific position, you can do it like this:

var name = "ferry Seinfeld";
char[] nameArray = name.ToArray();
nameArray[0] = 'J';
name = new string(nameArray);

Please look into Replace method of String and also look into StringBuilder class to see if those will suit your needs.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64