Problem with the indexer being read-only C #

1

I declare the following:

public string caracter  = new string(new char[1]);

But when I call it later and try to give it a value it does not leave me and it takes out an indexer error

caracter[0] = 27; //No me deja darle valores me saca el error 
  

Unable to assign property or indexer 'string.this [int]' because it is read-only

I appreciate some help, thank you very much

    
asked by jmtaborda 11.12.2018 в 16:57
source

2 answers

2

To define a string array you must do it in the following ways

string[] s_arr = new string[] { "A", "B", "C" };

or

string[] s_arr = new string[3];
s_arr[0] = "A";
s_arr[1] = "B";
s_arr[2] = "C";

If you need more information you can check the following link link

    
answered by 11.12.2018 / 17:12
source
2

Strings ( string ) in C # are immutable. This means that they can not be modified once created.

You could use StringBuilder , as follows:

StringBuilder caracter= new StringBuilder("");
caracter[0] = (char)27;

Although if, as it seems, you want to store a character, why not use char directly?

char c;
c=(char)27;

Edited

After reading your comment, another more logical option if you want an array of characters, is to use a char collection:

char[] caracteres = new char[10];
caracteres[6] = 's';

Edited 2

  

is to be able to implement an algorithm that reads numbers and prints the value in letters

In that case, what you should do is store the numbers in the collection (array, List ..) and only convert them to their representation later.

int[] numeros= new int[numerodeelementos];

o

List<int> numeros = new List<int>();
    
answered by 11.12.2018 в 17:09