Here is my sample code:
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
foreach (var i in numbers())
{
listBox1.Items.Add(i);
}
}
private List<int> numbers()
{
List<int> counts = new List<int>();
for (int i = 1; i <= 5; i++)
{
counts.Add(i);
}
return counts;
}
I want to know if it is possible to not overwrite and remain the previous values from a List<>. In my sample if I click the button it will populate 1,2,3,4,5 in the listbox and when I click the button again I am expecting an output of 1,2,3,4,5,1,2,3,4,5 this values is what I am expecting from my List<> How could I possibly do that? BTW, the listbox there is just for display purposes. Thanks!
With
List<int> counts = new List<int>();, you create a new, empty list. This happens anew with each call tonumbers().If I understand your question correctly, you want
numbers()to add the five numbers to an existing lists, that hence grows with each call tonumbers().In order to achieve this, do not create a new
List<int>with each call ofnumbers()that you return as a result value; instead create a private field for that list and modify it with each call tonumbers():Note that
numbers()will still return the list, but it’s not a new list; it’s the same list instance every time.