tags:

views:

1416

answers:

5

If I'm using an ArrayList in C#.NET, is the order guaranteed to stay the same as the order I add items to it?

+5  A: 

Yes, it is, unless some piece of your code changes the order by e.g. swapping.

Barry Kelly
+14  A: 

Yes, elements are always added to the end (unless you specify otherwise, e.g. with a call to Insert). In other words, if you do:

int size = list.Count;
int index = list.Add(element);
Assert.AreEqual(size, index); // Element is always added at the end
Assert.AreEqual(element, list[index]); // Returned index is position in list

The position will change if you remove any earlier elements or insert new elements ahead of it, of course.

Is there any good reason for you to use ArrayList rather than List<T> by the way? Non-generic collections are so 2003...

(The order is stable in List<T> as well, by the way.)

Jon Skeet
"Non-generic collections are so 2003..." - LOL, nice one Jon, that's going up as my quote of the week :)
DoctaJonez
+1  A: 

Yes. [silly answer length limit]

EBGreen
A: 

When you add an item to a ArrayList the item will always stay at that index. Unless of course if you change it.

(the framework might rearrange the memory but your index will always stay the same)

Y Low
+3  A: 

Yes it is. Since it's stored as an array.

Other properties are

  • Guaranteed order
  • Random access. You can access any element by index in O(1)
  • Slow insert and delete in the beginning and middle.
  • Unsorted. (Sorting should take O(n log n) using quicksort or similar)
Mats Fredriksson