Explain the difference between Array, ArrayList, and List<T>.

Beginner

Answer

Array:

  • Fixed size
  • Type-safe
  • Best performance
  • Zero-based indexing
    ArrayList:
  • Dynamic size
  • Stores objects (boxing for value types)
  • Not type-safe
  • Legacy, avoid in new code
    List:
  • Dynamic size
  • Type-safe with generics
  • No boxing for value types
  • Preferred choice for dynamic collections
// Array
int[] array = new int[5];
// ArrayList (avoid)
ArrayList arrayList = new ArrayList();
arrayList.Add(1);       // Boxing occurs
arrayList.Add("text");  // No compile-time type checking
// List<T> (preferred)
List<int> list = new List<int>();
list.Add(1);           // No boxing
// list.Add("text");   // Compile-time error