Sobes.tech
Senior

How does List differ from Array in C#?

sobes.tech AI

Answer from AI

In C# Array and List<T> are different data structures with different behaviors and purposes:

  • Array — fixed size, created with a specific length and cannot change size after creation. Array elements are accessible by index, and arrays are usually faster in performance.

  • List<T> — dynamic list, implemented as a wrapper over an array that automatically expands when new elements are added. It allows convenient adding, removing, and searching for elements.

Example:

int[] array = new int[3] {1, 2, 3};
// array[3] = 4; // Error, index out of range

List<int> list = new List<int> {1, 2, 3};
list.Add(4); // List size increased automatically

Main differences:

  • Size: array is fixed, List is dynamic.
  • Functionality: List provides methods for managing the collection (Add, Remove, Insert, etc.).
  • Usage: arrays are suitable for static data, List — for mutable collections.