Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to end of array C#?

Tags:

How do I add a new item from a TextBox and Button on a Windows Form at the end of an ArrayList which references a class?

private product[] value = new product[4];

value[1] = new product("One",5)
value[2] = new product("Two",3)
value[3] = new product("Three",8)

Workflow

  • Enter new products details into textbox1, textbox2, textbox3
  • When I click Add the new product gets added to the array:

    value[1] = new product("One",5)
    value[2] = new product("Two",3)
    value[3] = new product("Three",8)
    value[4] = new product("Four",2)

What is the code for doing this?

like image 989
Timmy Avatar asked Dec 03 '09 00:12

Timmy


People also ask

Can you add to arrays in C?

An array is a contiguous block of memory and if you want to append an element, you have to write it to the position following the last occupied position, provided the array is large enough.

How do I add elements to the end of an array in C ++?

C++ arrays aren't extendable. You either need to make the original array larger and maintain the number of valid elements in a separate variable, or create a new (larger) array and copy the old contents, followed by the element(s) you want to add.

What is at the end of an array in C?

C arrays don't have an end marker. It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size. If you do access an element outside the allocated size, the result is undefined behaviour.


1 Answers

Arrays are fixed size, which means you can't add more elements than the number allocated at creation time, if you need a auto sizing collection you could use List<T> or an ArrayList

Example:

// using collection initializers to add two products at creation time
List<Product> products = new List<Product>{new Product("One",5), new Product("Two",3) };

// then add more elements as needed
products.Add(new Product("Three",8));
like image 155
3 revs, 2 users 91% Avatar answered Jan 03 '23 16:01

3 revs, 2 users 91%