An ArrayList is better when you have heterogenous collections, or you need
dynamic list-like behavior. If you know that you have 5 instances of Apple,
use an array.
An instance of ArrayList can be sized dynamically:
ArrayList arrList = new ArrayList();
while(true)
arrList.Add(new Dollar());
A native C# array (which is an instance of System.Array) has a fixed size.
An ArrayList has elements of type object, which enables you to add any
element to your array (for good or evil):
arrList.Add(new Apple());
arrList.Add(new Orange());
arrList.Add(new JessicaSimpson());
A native C# array has elements of a specific type:
Apple[] arr = new Apple[2];
arr[0] = new Apple();
arr[1] = new Orange(); // compiler error
In addition to Peter's comments, ArrayLists are always generic
containers, whereas arrays can be type-specific (you can't put a string
value into an array of int, for example). The other thing to know is that
value types (ints, longs, enums, structs, etc.) get "boxed" going into an
ArrayList and "unboxed" coming out of an ArrayList. A lot of boxing and
unboxing can have negative performance implications.
An ArrayList is better when you have heterogenous collections, or you need
dynamic list-like behavior. If you know that you have 5 instances of Apple,
use an array.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.