Sobes.tech
Junior

What is the difference between ArrayList and List in C#?

sobes.tech AI

Answer from AI

The differences between ArrayList and List in C# are as follows:

  • Typing:

    • ArrayList stores elements of type object (non-generic collection), which requires casting when retrieving elements and reduces type safety.
    • List<T> is a generic collection (T is a specified type), stores elements of a strictly defined type, ensuring type safety and eliminating the need for casting.
  • Performance:

    • Adding and retrieving elements in ArrayList can be slower due to boxing and unboxing of value types.
    • List<T> is generally faster, especially for value types, as it avoids boxing/unboxing.
  • Type Safety:

    • ArrayList can contain elements of different types, which may lead to runtime errors.
    • List<T> provides compile-time type safety.
  • Implementation:

    • ArrayList resides in the System.Collections namespace.
    • List<T> resides in the System.Collections.Generic namespace.
  • Usage:

    • ArrayList is considered obsolete and is not recommended for use in new code.
    • List<T> is the preferred choice for most scenarios.

Example usage:

// Using ArrayList
System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
arrayList.Add(1);       // int is boxed into object
arrayList.Add("string"); // string is stored as object

int number = (int)arrayList[0]; // Casting is required

// Using List<T>
System.Collections.Generic.List<int> list = new System.Collections.Generic.List<int>();
list.Add(1); // Adding int

// int number = list[0]; // No casting needed

Comparison table:

Attribute ArrayList List<T>
Typing Non-typed (object) Generic (T)
Performance Possible boxing/unboxing Higher, no boxing/unboxing for value types
Type Safety Low High (at compile time)
Namespace System.Collections System.Collections.Generic
Recommendation Not recommended Recommended