ArrayList: A Dynamic Collection in C#

ArrayList: A Dynamic Collection in C#

When you are on a buffet, you want to try all dishes, but you feel full after few items, and you wish to have some more space, right? If similar situation happens while coding, don’t worry we have ArrayList.

An ArrayList is a non-generic collection in C# that can store objects of any data type. It's dynamic, meaning it can grow or shrink in size as needed.

Key Features:

  • Dynamic Resizing: Automatically adjusts its size to accommodate new elements.

  • Object Storage: Can store objects of any data type.

  • Zero-Based Indexing: Elements are accessed using an integer index starting from 0.

ArrayList myList = new ArrayList();
// Add elements of different data types
myList.Add("Apple");  // Adding a string
myList.Add(10);       // Adding an integer
myList.Add(3.14);     // Adding a double

object firstElement = myList[0]; // Access the first element

//Iterating Through Elements:
foreach (object item in myList)
{
    Console.WriteLine(item);
}

myList.Remove("Apple"); // Removes the first occurrence of "Apple"
myList.RemoveAt(1); // Removes the element at index 1

// Clearing the ArrayList
// myList.Clear();

Important Considerations:

  • Type Safety: ArrayLists are not type-safe. You need to cast elements to their correct type when retrieving them. This can lead to runtime errors if not handled carefully.

  • Performance: Due to boxing and unboxing, ArrayLists can be less performant compared to generic collections like List<T>.

When to Use ArrayList:

While ArrayLists are still available, they are generally not recommended for modern C# development. Generic collections like List<T> offer better type safety, performance, and readability.

However, in legacy code or specific scenarios where you need to store different data types in a single collection without knowing the types beforehand, ArrayLists might still be useful.