How to Use ArrayList in C# with Example?

In C# programming, the ArrayList is a versatile data structure that allows for the dynamic management of data collections. Unlike arrays that require a predefined size, ArrayList in C# adjusts its size automatically as elements are added or removed.

To effectively use an ArrayList in C#, developers must understand its methods and properties. The class provides a range of functionalities, including adding and removing items, searching, sorting, and accessing individual items.

In this C# tutorial, I will explain how to use ArrayList in C# with examples.

What is an ArrayList in C#?

An ArrayList in C# is a non-generic collection, residing in the System.Collections namespace, capable of holding elements of any data types. It is similar to an array but offers more flexibility by allowing dynamically adding or removing elements.

Key Properties and Methods:

  • Count: Gets the actual number of elements in the ArrayList.
  • Capacity: Gets or sets the number of elements the ArrayList can contain.
  • IsFixedSize: Indicates whether the ArrayList has a fixed size.
  • IsReadOnly: Indicates if the ArrayList is read-only.

Adding Elements:

  • Add(object value): Adds an element to the end of the ArrayList.
  • AddRange(ICollection c): Adds the elements of an ICollection to the end of the ArrayList.

Removing Elements:

  • Remove(object value): Removes the first occurrence of a specific object.
  • RemoveAt(int index): Removes the element at the specified index.

Accessing Elements: Elements are accessed via the indexer, arrayList[index].

Example of Creating and Using an ArrayList:

// Creating an ArrayList
ArrayList myArrayList = new ArrayList();

// Adding elements to the ArrayList
myArrayList.Add(1);
myArrayList.Add("Two");
myArrayList.Add(3.0);

// Removing an element by specifying its value
myArrayList.Remove("Two");

// Accessing an element by index
int firstElement = (int)myArrayList[0];

// Displaying the count of elements
Console.WriteLine(myArrayList.Count);

ArrayLists provide the advantage of being able to hold elements of various data types, but lack the type safety provided by generic collections such as List<T>. It is recommended to use generic collections for type safety and better performance unless non-generic collections are specifically required.

To practice all these examples, you can create a C# console or Windows applications using Visual Studio.

Create an ArrayList in C#

An ArrayList in C# is a dynamic array that can hold items of various types. It offers a flexible way to manage collections that can change in size.

Instantiating an ArrayList

To instantiate an ArrayList, one must first include the System.Collections namespace and then create an instance of the ArrayList class. Here is an example of instantiation:

using System.Collections;

ArrayList myArrayList = new ArrayList();

This code creates a new, empty ArrayList named myArrayList.

Adding Elements to an ArrayList

Elements can be added to an ArrayList using the Add method. This method allows for adding elements of different types, as ArrayList does not require all elements to be of the same type.

myArrayList.Add(1); // Adds an integer
myArrayList.Add("Hello"); // Adds a string
myArrayList.Add(3.14); // Adds a double

To visualize the contents of the ArrayList after these operations, one might pictorially represent it as follows:

IndexValue
01
1“Hello”
23.14

Access C# ArrayList Elements

In C#, elements within an ArrayList can be accessed directly by index or by iterating through the collection.

Using Indexes

One can access an element in an ArrayList using an integer index. This index is zero-based, meaning the first element is at index 0, the second at index 1, and so on. For example, to get the element at the first position:

ArrayList myList = new ArrayList();
myList.Add("First");
myList.Add("Second");
string firstElement = (string)myList[0]; // Cast is required as ArrayList is not strongly typed

Attempting to access an index beyond the bounds of the ArrayList (e.g., using an index greater than or equal to the length of the ArrayList) will throw an ArgumentOutOfRangeException.

Using Iteration Techniques

Iterating over the elements of an ArrayList allows for a series of operations to be performed on each element. A common method of iteration is using a foreach loop, which provides a simple syntax for iterating over all elements:

foreach (var item in myList)
{
    // item is automatically of type Object because ArrayList is not strongly typed
    // Perform operations on item
}

For more control during iteration, such as when the index of the current element is needed, a for loop can be used:

for (int i = 0; i < myList.Count; i++)
{
    // Use i to access elements by index
    object item = myList[i];
    // Perform operations on item
}

C# ArrayList Manipulation

In C#, ArrayList provides dynamic array functionality, allowing for flexible management of elements. They can manipulate elements by removing, inserting, or sorting with ease.

Removing Elements

One can remove elements from an ArrayList either by specifying the index or the actual element. The RemoveAt method is used for removing an element at a particular index, while Remove method is used to remove a specific element. Here’s an example:

ArrayList myList = new ArrayList();
myList.Add("First");
myList.Add("Second");
myList.Add("Third");

// Remove element at index 1
myList.RemoveAt(1); 

// Remove the element "Third"
myList.Remove("Third");

Inserting Elements at Specific Positions

To insert an element at a specified index in an ArrayList, the Insert method is used. It shifts the current element and any subsequent elements to the next higher index. For example:

ArrayList myList = new ArrayList();
myList.Add("First");
myList.Add("Third");

// Insert "Second" at index 1
myList.Insert(1, "Second");

Sorting and Searching Elements

ArrayList can be sorted using the Sort method and searched using methods like BinarySearch or IndexOf. The Sort method orders the elements or a portion of the elements. BinarySearch is efficient on sorted lists to find an element, while IndexOf searches for the element from the beginning of the list.

ArrayList myList = new ArrayList();
myList.Add("Cherry");
myList.Add("Apple");
myList.Add("Banana");

// Sort the ArrayList
myList.Sort(); // myList: ["Apple", "Banana", "Cherry"]

// Search for an element
int index = myList.BinarySearch("Banana"); // index: 1

Convert C# ArrayList to Array

Converting an ArrayList to an array in C# can be easily achieved using the ToArray method. It is important to handle type casting correctly to avoid runtime errors.

Using the ToArray() Method

The ToArray method is provided by the ArrayList class to convert an ArrayList into a standard array. Here is how one can utilize this method:

ArrayList arrayList = new ArrayList();
arrayList.Add(1);
arrayList.Add(2);
arrayList.Add(3);

// Converting ArrayList to an array
object[] array = arrayList.ToArray();

Handling Type Casting

When an ArrayList is converted to an array, elements are of the object type. For a strongly typed array, explicit casting is necessary:

// Assuming the ArrayList only contains integers
int[] intArray = new int[arrayList.Count];
array.CopyTo(intArray, 0);

It should be noted that attempting to cast to an incorrect type will result in a InvalidCastException. Therefore, the types of elements in the ArrayList must be known and consistent before casting.

Examples of C# ArrayList

Here is a complete example of how to use an ArrayList in C#. The following C# code snippet demonstrates the use of ArrayList:

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        // Initializing an ArrayList
        ArrayList numbers = new ArrayList();

        // Adding elements to the ArrayList
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);

        // Removing the element '2'
        numbers.Remove(2);
        
        // Iterating over the ArrayList
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

This example shows initializing an ArrayList, adding elements to it, removing an element, and traversing over the ArrayList to print each element.

Once you executed the code using a console application, you can see the output like below:

ArrayList in C#

Conclusion

ArrayLists in C# offer a dynamic way to handle collections that can be resized and modified with ease. In this C# tutorial, I have explained how to use ArrayLists in C# with examples.

You may also like: