52

I am wondering what the exact difference is between a Array, ArrayList and a List (as they all have similar concepts) and where you would use one over the other.

Example:

Array
For the Array we can only add types that we declare for this example an int.

int[] Array = new Int[5]; //Instansiation of an array
for(int i = 0; i < Array.Length; i++)
{
   Array[i] = i + 5; //Add values to each array index
}

ArrayList
We can add values just like a Array

ArrayList arrayList = new ArrayList();
arrayList.Add(6);
arrayList.Add(8);

List
Again we can add values like we do in an Array

List<int> list = new List<int>();
list.Add(6);
List.Add(8);

I know that in a List you can have the generic type so you can pass in any type that you cannot do in an Array but my exact questions are:

  • Where would you use one over the other?
  • The exact difference functionality wise between the three?
2

1 Answer 1

126

They are different object types. They have different capabilities and store their data in different ways.

An Array (System.Array) is fixed in size once it is allocated. You can't add items to it or remove items from it. Also, all the elements must be the same type. As a result, it is type safe, and is also the most efficient of the three, both in terms of memory and performance. Also, System.Array supports multiple dimensions (i.e. it has a Rank property) while List and ArrayList do not (although you can create a List of Lists or an ArrayList of ArrayLists, if you want to).

An ArrayList is a flexible array which contains a list of objects. You can add and remove items from it and it automatically deals with allocating space. If you store value types in it, they are boxed and unboxed, which can be a bit inefficient. Also, it is not type-safe.

A List<> leverages generics; it is essentially a type-safe version of ArrayList. This means there is no boxing or unboxing (which improves performance) and if you attempt to add an item of the wrong type it'll generate a compile-time error.

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

5 Comments

Perfect answer!
ArrayList extends AbstractList and implements List Interface. Or it is some other list meant?
@Yan That's Java. This question is about c#.
@JohnWu, oh, I see, my mistake, sorry.
Nice! Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.