C# ArrayList

C#  C#  arraylist 

C# ArrayList is a non-generic dynamic size collection class. ArrayList class exists in System.Collections namespace. ArrayList are dynamic means we can add any number of items without specifying the size of it.

ArrayList vs Array

ArrayList and Array looks same. But there are some major differences between them. Differences are:

  1. Array is fixed in size. We specify the size of array at its instantiated time.
  2. We can only store same type of data in Array. But ArrayList is based on the object. So we can store any type of data whether it is int, string, double, or any custom data type.

ArrayList vs List<>

ArrayList and List<> are both arrays. Both are used for storing items. But there are some important differences between them.

  1. ArrayList are not type-safe. Generic List is type-safe.
  2. ArrayList has in-built synchronization mechanism. Generic List does not have synchronization mechanism. User has to implement its own synchronization mechanism for using it.
  3. List<> provides better performance.

Below are the some operations we can do with it.

Creating an ArrayList

Below is the example of creating it.

ArrayList arr = new ArrayList();

Adding Items

For adding new items, we can use the Add method which takes the object as parameter. That means we can store any type of items in the list.

arr.Add("First");
arr.Add("Second");

Add Items from another List

We can use the AddRange method for this work. AddRange takes the ICollection object as parameter. We have two ArrayList arr and arr2. As ArrayList implements the ICollection interface we can combine both lists using AddRange method.

ArrayList arr = new ArrayList();
arr.Add("First");
arr.Add("Second");
arr.Add("Third");
arr.Add("Fourth");
arr.Add("Fifth");

ArrayList arr2 = new ArrayList();
arr2.Add("Sixth");
arr2.Add("Seventh");

arr.AddRange(arr2);

/// Items in ArrayList
/// First
/// Second
/// Third
/// Fourth
/// Fifth
/// Sixth
/// Seventh

Capacity

ArrayList has a Capacity property. This capacity property lets CLR know how much space should be allocated. Capacity is only indication to CLR it doesn't stop you to add more items than Capacity. By default this Capacity is Zero(0). You can specify capacity by using constructor or by setting the Capacity property.

ArrayList arr = new ArrayList();
Console.WriteLine(arr.Capacity);  //Returns 0;

When you'll add more items than the capacity, then capacity is automatically increased.

ArrayList arr = new ArrayList(5);   //Setting Capacity 5
arr.Add("First");
arr.Add("Second");
arr.Add("Third");
arr.Add("Fourth");
arr.Add("Fifth");
arr.Add("Sixth");

Console.WriteLine(arr.Capacity);    //Returns 10;

Get total records count

For counting the total records in ArrayList, we can use the property Count like shown below:

int totalRecords = arr.Count;

For retrieving single record

For accessing the single record, you can use the indexers like shown below:

string firstValue = (string)arr[0];

As arr returned object, we have to cast the result to string to assign that to string variable.

Get all records

ArrayList implements the IEnumerable interface. We can use foreach loop to iterate over it.

foreach(object obj in arr)
{
    Console.WriteLine(obj.ToString());
}

Or we can simply use for loop using Count property like shown below:

for (int i = 0; i < arr.Count; ++i)
{
    Console.WriteLine(arr[i].ToString());
}

Insert new item at specific Index

ArrayList store its first item at zero(0) index. That means second item is 1st index and third is in 2nd index. Add method allows us to add items at (last inserted item index + 1) index. But sometimes, we have to insert item at in the middle of it. For that, ArrayList provides an Insert method to store item at specific index.

ArrayList arr = new ArrayList();
arr.Add("First");
arr.Add("Second");
arr.Add("Fifth");
arr.Add("Sixth");

arr.Insert(2, "Third");
arr.Insert(3, "Fourth");

foreach (object obj in arr)
{
    Console.WriteLine(obj.ToString());
}

/// Result:
/// First
/// Second
/// Third
/// Fourth
/// Fifth

In the above code, we have added four items. But we have to add two new items after the "Second" value. So we used Insert method and give the index of 2 and 3 to insert data. "Fifth" and "Sixth" values that are stored previously in index 2 and 3 are now moves to index 4 and 5.

Add multiple items at particular index

In the previous section, we have store only single item at a time at particular index. But if we need to store multiple items starting from particular index. Then we have to use a new method InsertRange method like shown below:

ArrayList arr = new ArrayList();
arr.Add("First");
arr.Add("Second");
arr.Add("Fifth");
arr.Add("Sixth");

ArrayList arr2 = new ArrayList();
arr2.Add("Third");
arr2.Add("Fourth");

arr.InsertRange(2, arr2);

foreach (object obj in arr)
{
    Console.WriteLine(obj.ToString());
}

/// Result:
/// First
/// Second
/// Third
/// Fourth
/// Fifth
/// Sixth

In the above example, we have two items "Third" and "Fourth" in different array. We have to store that array into ArrayList at index 2. We used InsertRange method and give the starting index as 2.

Remove item

For removing an item, we have three methods:

  1. Remove(object obj): Removes single item by matching the parameter.
  2. RemoveAt(int index): Removes the single item at particular index.
  3. RemoveRange(int index, int count): Removes multiple items from particular index.

RemoveRange method removes number of items specify in the count parameter. For example, if count has value of 3 and index is 1 then it removes starting from index 1 and remove three items which is at index 1st, 2nd, and 3rd.

Below is the example of all three methods.

ArrayList arr = new ArrayList();
arr.Add("First");
arr.Add("Second");
arr.Add("Third");
arr.Add("Fourth");
arr.Add("Fifth");

arr.Remove("First"); //Remove 'First' item

ArrayList arr2 = new ArrayList();
arr2.Add("First");
arr2.Add("Second");
arr2.Add("Third");
arr2.Add("Fourth");
arr2.Add("Fifth");

arr2.RemoveAt(1);   //Remove 'Second' item


ArrayList arr3 = new ArrayList();
arr3.Add("First");
arr3.Add("Second");
arr3.Add("Third");
arr3.Add("Fourth");
arr3.Add("Fifth");

arr3.RemoveRange(1, 2); //Remove 'Second' and 'Third' item

Clear all items from the list

To clear all items, we have to use Clear method of list. Below is the example program:

ArrayList arr = new ArrayList();
arr.Add("First");
arr.Add("Second");
arr.Add("Third");
arr.Add("Fourth");
arr.Add("Fifth");

arr.Clear();

int totalCount = arr.Count; //Return 0;

ArrayList Sorting

ArrayList provides a Sort method which use Quicksort algorithm internally to sort the items. Below is the example of sorting.

ArrayList arr = new ArrayList();
arr.Add("9");
arr.Add("2");
arr.Add("3");
arr.Add("7");
arr.Add("1");

arr.Sort();

foreach (object obj in arr)
{
    Console.WriteLine(obj.ToString());
}

/// Result:
/// 1
/// 2
/// 3
/// 7
/// 9

Reverse all items

Reverse method simply reverse the list items. For example, if total number of items are 6. Then it exchanges the index 0th item with 5th index item and 1st item to 4th index item and 2nd item to 3rd index item.

ArrayList arr = new ArrayList();
arr.Add("9");
arr.Add("2");
arr.Add("3");
arr.Add("7");
arr.Add("1");

arr.Reverse();

foreach (object obj in arr)
{
    Console.WriteLine(obj.ToString());
}

/// Result:
/// 1
/// 7
/// 3
/// 2
/// 9

Search item in the list

For searching an item into the list, we have BinarySearch method. It returns the index of search item. If it does not found any item then it returns the result in minus.

For searching the list, first we have to sort the list using Sort method as BinarySearch will always work only on sorted list.

ArrayList arr = new ArrayList();
arr.Add("9");
arr.Add("2");
arr.Add("3");
arr.Add("7");
arr.Add("1");

arr.Sort();
int foundIndex = arr.BinarySearch("3"); //Returns 2

Use ArrayList in multi-threaded scenarios

ArrayList is not thread-safe. Below is the example where two threads are accessing ArrayList. First thread is enumerating the list and second thread is adding item to the list.

ArrayList arr = new ArrayList();
arr.Add("9");   // default item

var t1 = Task.Factory.StartNew(() =&amp;gt;
    {
        while (true)
        {
            Console.WriteLine("");
            foreach (object obj in arr)
            {
                Console.Write(obj.ToString() + ",");
            }

            if(arr.Count == 11)
            {
                break;
            }
            Thread.Sleep(100);
        }
    });

var t2 = Task.Factory.StartNew(() =&amp;gt;
    {
        for (int i = 10; i &amp;lt; 20; ++i)
        {
            arr.Add(i);
            Thread.Sleep(100);
        }
    });

Task.WaitAll(new Task[] { t1, t2 });

Above example fails with "Collection as modified, enumeration operation may not execute" error.

To use ArrayList in multi-threading environment, we must lock the ArrayList. For that when we enumerate the list, list should not be modified. ArrayList provides a SyncRoot object for synchronization. Below is the example of SyncRoot.

ArrayList arr = new ArrayList();
arr.Add("9");   // default item

var t1 = Task.Factory.StartNew(() =>
    {
        while (true)
        {
            lock (arr.SyncRoot)
            {
                Console.WriteLine("");
                foreach (object obj in arr)
                {
                    Console.Write(obj.ToString() + ",");
                }
            }
            if (arr.Count == 11)
            {
                break;
            }
            Thread.Sleep(100);
        }
    });

var t2 = Task.Factory.StartNew(() =>
    {
        for (int i = 10; i < 20; ++i)
        {
            lock (arr.SyncRoot)
            {
                arr.Add(i);
            }
            Thread.Sleep(100);
        }
    });

Task.WaitAll(new Task[] { t1, t2 });

Final Words

ArrayList is used for storing different types of heterogeneous data. It works on the object type so it will downgrade performance. You have to casting when you want the result back. ArrayList have some good features like Sort, Reverse and synchronization that are not available in any other collection class. It is an older data type and generic List or array can provide better performance than it.

Join our newsletter and get an occasional email with a technology and dotnetpattern.com news update.