How to add to end of array C#?

Viewed 75724

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?

7 Answers

Array.Resize is not an efficient method. It creates a new array with the new size then copy old array values to the new array and then replaces the old array with the new array. As you can see this is not a very efficient way of appending an item.

Unless it is a requirement that you have no control on use a List instead of array or create an array with maximum expected dimension from the beginning.

For more explanation consider this example: You created an array that can hold million items and fill it with objects. You want to add the million and one object to the array. You use Array.Resize method to change array size to 1000001. When the method tries to create a new array of 1000001 items and copy the items from old array to new array you may get an out of memory error because you are trying to have TWO arrays of a million (holding 2 millions objects) in memory at the same time while all the items that you need are one million +1. Although consider the time and resources lost in creating, copying and replacing.

Related