C # Help with static variables

2

I do not have much experience with C # and Forms but I have a problem with static variables. I need a static int variable to define the size of a static array.

Public partial class Form1 : Form
    {
        public Form1()
        {
        InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
        cont(Box.Text);
        }

        static int c = 0;

        static string[] elementos = new string[c+1];

        static void cont(string var1)
        {     
        elementos[c]= var1;
        MessageBox.Show(elementos[c]);
        c += 1;     
        }   

    } 

I need the static "int c = 0" to work as the array size "static string [] elements = new string [c +1]" but throws the following error "Index outside the boundaries of the array."

How do I get one static variable to work with another variable?

    
asked by Jhonatan Zu 28.09.2018 в 03:41
source

3 answers

1

The problem is that you think that by defining array using another variable, it will grow when said variable grows. That is NOT so.

The size of array is defined when you declare the variable. In your code, elementos will ALWAYS be a% co_of% of size 1.

You have several options at this point. On the one hand, if you insist on using array , you can use the method Array to change the size. I do not recommend it, because this method eliminates the array to recreate it, and the performance is quite poor.

If what you want is a collection that grows as you insert elements, there are many better options in .NET.

The best thing in this case is to use Array.Resize . In your case, define a List<T>

List<int> elementos= new List<int>();
void cont(string var1)
{     
    elementos.Add(var1);
    MessageBox.Show(elementos.Last());
}  
    
answered by 28.09.2018 / 09:06
source
2

Here you specify that the size of the variable elements is 1.

static string[] elementos = new string[c];

But later you try to put a value in index 1.

elementos[c]= var1;

The problem is that you are trying to put a value outside the limit. You should do something like this:

elementos[c-1]= var1;

Since the index of an array starts at 0, not at 1 (as you try to do in your code).

    
answered by 28.09.2018 в 03:49
0

If you need your array to be of an indefinite size it would be better if you used lists. Let's say you want to use an array of strings, in this case you would declare a list like this

List<String> lista = new List<String>();

Para agregar un elemento a la lista usarías

string cadena = "mi cadena";
lista.Ad(cadena);

para recorrer la lista lo puedes hacer con un foreach así

foreach(string str in lista)
{
    MessageBox.Show(str);
}
    
answered by 28.09.2018 в 03:59