Skip to main content
Published on

ArrayList Class in C#

Share:

Introduction

In the programming world, we are always looking for tools that allow us to store and manipulate data efficiently. In C#, one such tool is the ArrayList class.

What is ArrayList?

First of all, it is essential to understand what an ArrayList is. Unlike traditional fixed-size arrays, the ArrayList is a dynamic collection of objects. It belongs to the System.Collections namespace and is known for its ability to automatically adjust its size.

ArrayList Characteristics:

  1. Dynamic: There is no need to define a size at the time of creation.
  2. Object Type: It stores objects of type object, allowing different types of data to be stored.
  3. Ordered: Elements are accessed by index and kept in order.

Manipulating Data with ArrayList

The ArrayList class provides several methods to facilitate the management of stored elements:

using System;
using System.Collections;

namespace Base {
  class ArrayListClass {
    private ArrayList schoolSupplies = new ArrayList() {
      "Backpack",
      "Pencil Case",
      "Pencil",
      "Eraser"
    };

    public void Run() {
      // Adding elements
      schoolSupplies.Add("Sharpener");
      schoolSupplies.Add("Scissors");

      // Removing a specific element
      schoolSupplies.Remove("Backpack");

      // Reversing the order
      schoolSupplies.Reverse();

      // Display the number of elements
      Console.WriteLine($"Number of school supplies: {schoolSupplies.Count}");

      // Display all elements
      foreach (var schoolSupply in schoolSupplies)
        Console.WriteLine($"School supply: {schoolSupply}");
    }
  }
}

Benefits and Limitations

The ArrayList has several advantages, such as flexibility and ease of use. However, it is not without limitations:

  1. Performance: Because it is of type object, there can be performance costs associated with boxing and unboxing.
  2. Typing: The lack of strong typing can lead to runtime errors.

For many applications, List<T> can be a more efficient alternative, as it is strongly typed.

When to use ArrayList?

Despite its limitations, the ArrayList is useful when you need a dynamic collection without committing to a specific data type. It is especially valuable in scenarios where the data to be stored is heterogeneous or when you are not sure about the amount of data.

Conclusion

Understanding the various tools available is crucial for any programmer. The ArrayList class is one of those tools in C#. It offers great flexibility, but, like all tools, it must be used in the right context.

Happy coding!