I'm doing a windows form app and I need to declare empty array for some listbox operations. But i can't add value to array. When I try to print the lenght of the array after adding a value I reading the value 0 all the time.
public partial class Form1 : Form
{
public static int[] arrayOfNumbers = new int[] { };
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
arrayOfNumbers.Append(Convert.ToInt32(textBox1.Text));
Console.WriteLine(arrayOfNumbers.Length);
}
CodePudding user response:
Enumerable.Append
appends an item to a sequence and returns it, so you need to use it to re-assign a new array to the field. But it doesn't return an arrray but IEnumerable<T>
, so you have to append ToArray
:
arrayOfNumbers = arrayOfNumbers.Append(Convert.ToInt32(textBox1.Text)).ToArray();
Arrays are a fixed size collection which you can't modify anyway.