0

Whenever I need to add an element to an array I've always used this algorithm

data toAdd = 10;

data[] theArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

data[] tempArray = new int[theArray.Length + 1];

for (int i = 0; i < theArray.Length; i++)
{
    tempArray[i] = theArray[i];
}

theArray = new data[tempArray.Length];

for (int i = 0; i < theArray.Length; i++)
{
    theArray[i] = tempArray[i];
}

theArray[theArray.Length - 1] = toAdd;

However I was wondering if there was a better way to do this, as with much larger arrays this will require a large amount of computing time.

1
  • 2
    Arrays are fixed-size, List<T> (or any of a multitude of other collections) aren't. First verify if you're trying to screw something with a hammer. Then look at Array.Copy. Commented Jan 1, 2015 at 20:18

1 Answer 1

0

You could use Array.Resize. But you should really use an ArrayList or List<> which do this much more easily and effectively.

Sign up to request clarification or add additional context in comments.

1 Comment

Upvoted. But don't use ArrayList, prefer the generic List<>.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.