A2oz

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

Published in Programming Languages 2 mins read

The primary difference between a List and an ArrayList in C# lies in their underlying data structures and type safety.

List

  • List is a generic collection that provides a strongly typed, resizable array.
  • List is part of the System.Collections.Generic namespace and is designed for storing elements of a specific data type.
  • List offers a wide range of methods for adding, removing, searching, and manipulating elements efficiently.
  • List is generally preferred over ArrayList due to its type safety, performance benefits, and better code readability.

ArrayList

  • ArrayList is a non-generic collection that can hold elements of any data type.
  • ArrayList belongs to the System.Collections namespace and allows for dynamic resizing, accommodating varying numbers of elements.
  • ArrayList is less efficient than List due to its boxing and unboxing operations when handling different data types.
  • ArrayList is considered a legacy class and is generally discouraged for new development, as it can lead to runtime errors and decreased code clarity.

Example:

// List example
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");

// ArrayList example
ArrayList numbers = new ArrayList();
numbers.Add(1);
numbers.Add(2.5);
numbers.Add("Three");

In this example, the List named names can only hold strings, ensuring type safety. On the other hand, the ArrayList named numbers can store integers, floating-point numbers, and strings, potentially leading to type-related errors.

In summary, List is the preferred choice for most scenarios due to its type safety, performance, and compatibility with generic programming. ArrayList should be avoided in new code, as it lacks type safety and can introduce runtime errors.

Related Articles