Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use ArrayList over array[] in c#?

I often use an ArrayList instead of a 'normal' array[].

I feel as if I am cheating (or being lazy) when I use an ArrayList, when is it okay to use an ArrayList over an array?

like image 357
Ian G Avatar asked Jan 05 '09 11:01

Ian G


1 Answers

Arrays are strongly typed, and work well as parameters. If you know the length of your collection and it is fixed, you should use an array.

ArrayLists are not strongly typed, every Insertion or Retrial will need a cast to get back to your original type. If you need a method to take a list of a specific type, ArrayLists fall short because you could pass in an ArrayList containing any type. ArrayLists use a dynamically expanding array internally, so there is also a hit to expand the size of the internal array when it hits its capacity.

What you really want to use is a generic list like List<T>. This has all the advantages of Array and ArrayLists. It is strongly typed and it supports a variable length of items.

like image 190
Bob Avatar answered Oct 20 '22 10:10

Bob