Difference between Array and ArrayList in C#

By FoxLearn 2/7/2025 3:21:46 AM   56
In C#, both Array and ArrayList are used to store collections of elements.

However, they have significant differences in terms of flexibility, type-safety, and performance.

ArrayArrayList
Requires System namespace to use arrays.Requires System.Collections namespace to use ArrayList.
Array Declaration & Initialization:
int[] arr = new int[5];
int[] arr = new int[5]{1, 2, 3, 4, 5};
int[] arr = {1, 2, 3, 4, 5};
ArrayList Declaration & Initialization:
ArrayList arList = new ArrayList();
arList.Add(1);
arList.Add("Two");
arList.Add(false);
Array size is fixed. The number of elements must be defined when the array is created.ArrayList dynamically resizes as elements are added or removed. You don't need to specify the size at initialization.
Arrays are strongly typed, meaning they can only store elements of a specified type.ArrayList is not strongly typed and can store elements of any type (e.g., integers, strings, booleans, etc.).
No need to cast elements when accessing an array because it stores elements of a single, defined type.Elements in an ArrayList often need to be cast to the appropriate type when accessed, resulting in boxing and unboxing when dealing with value types.
Performance: Arrays generally perform faster than ArrayList because they are strongly typed and don't require boxing/unboxing.Performance: ArrayList tends to be slower due to the overhead of boxing/unboxing and dynamic resizing.
Use static helper class Array for various tasks like sorting, searching, etc.ArrayList includes built-in methods for tasks like adding, removing, and searching elements.

For example, C# Array:

using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        Console.WriteLine(numbers[2]); // Accessing an element in the array
    }
}

For example, C# ArrayList:

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList arList = new ArrayList();
        arList.Add(1);
        arList.Add("Two");
        arList.Add(true);        
        Console.WriteLine(arList[1]); // Accessing an element in ArrayList
    }
}

Key Differences:

  • Array is fixed in size, ArrayList dynamically resizes.
  • Array is type-specific, while ArrayList can hold any data type.
  • Array is generally faster and more efficient, while ArrayList offers more flexibility at the cost of performance.