ArrayList in C#

The ArrayList class implements a collection of objects using an array whose size is dynamically increased as required. The ArrayList class is very useful if you are working with arrays and need to add, remove, index, or search for data in a collection.

Although ArrayList is very versatile and grows dynamically when you add values, it is slower than the Array class, which allows you to access its members with subscripts but does not let the array grow during runtime. When choosing between Array and ArrayList, decide which feature is important to your application. To get a better idea of how an Array compares to an ArrayList, think of an ArrayList as nothing more than a linked-list implementation of an Array. Adding data to an ArrayList is pretty easy; just call the class's Add member, as shown in Listing 20.17.

Listing 20.17: Adding an element to an ArrayList

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace systemArrayListClass
{

    class Program
    {

        static void Main(string[] args)
        {
            ArrayList dataArray = new ArrayList();

            for (int i = 0; i < 20; i++)
            {
                dataArray.Add(i);
            }

            // or you can add any object type like below.
            dataArray.Add("Object type");
        }
    }
}

The Add member takes an argument of Object type. You can add any value to the ArrayList because all values inherit from the Object base class.

You can also insert an element into the ArrayList at a specified index. Note that if you specify the index item as the last item + 1, the Insert method works the same way as the Add method:

myList.Insert(1, "real first");

The Remove and RemoveAt members delete data from an ArrayList. The RemoveAt method removes the element at the specified index of the ArrayList, while the Remove method removes the first occurrence of a specific object from the ArrayList:

// Remove the element containing "3".
myList.Remove( "3" );

The BinarySearch member of ArrayList is very useful and fast for searching for elements. This member returns the zero-based index of a specific element in the sorted ArrayList or a portion of it using a binary search algorithm:

int myIndex = myList.BinarySearch(3);

With the ToArray function, you can copy the elements of the ArrayList to a new array of the specified type:

int[] myIntArr = myList.ToArray(Int32);

You can always set the capacity to the actual number of elements in the ArrayList with the TrimToSize function:

myList.TrimToSize();

Further Readings

Here are some more articles related to ArrayList and Arrays that you may be interested in.

Conclusion

Hope this article would have helped you in understanding the System.ArrayList Class using C#. See other articles on the website on .NET and C#.


Similar Articles