C# - ArrayList

ArrayList is a non-generic type of collection in C#. It can contain elements of any data types. It is similar to an array, except that it grows automatically as you add items in it. Unlike an array, you don't need to specify the size of ArrayList.

The following diagram illustrates the ArrayList class hierarchy.

C# ArrayList

As you can see from the above diagram, the ArrayList class implements IEnumerable, ICollection, and IList interfaces. So, you can create an object of ArrayList class and assign it to the variable of any base interface type. However, if you assign it to IEnumerable or ICollection type variable then you won't be able to add elements and access ArrayList by index.

Example: Create ArrayList
ArrayList myArryList1 = new ArrayList();// Recommended
// or - with some limitations
IList myArryList2 = new ArrayList();
// or - with some limitations
ICollection myArryList3 = new ArrayList();
// or - with some limitations
IEnumerable myArryList4 = new ArrayList();

It is recommended to use ArrayList type of variable for ArrayList object because ArrayList class contains some additional methods which are not the members of IList interface such as AddRange(), BinarySearch(), Repeat(), Reverse(), etc.

Important Properties and Methods of ArrayList

Properties Description
Capacity Gets or sets the number of elements that the ArrayList can contain.
Count Gets the number of elements actually contained in the ArrayList.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly Gets a value indicating whether the ArrayList is read-only.
Item Gets or sets the element at the specified index.
Methods Description
Add()/AddRange() Add() method adds single elements at the end of ArrayList.
AddRange() method adds all the elements from the specified collection into ArrayList.
Insert()/InsertRange() Insert() method insert a single elements at the specified index in ArrayList.
InsertRange() method insert all the elements of the specified collection starting from specified index in ArrayList.
Remove()/RemoveRange() Remove() method removes the specified element from the ArrayList.
RemoveRange() method removes a range of elements from the ArrayList.
RemoveAt() Removes the element at the specified index from the ArrayList.
Sort() Sorts entire elements of the ArrayList.
Reverse() Reverses the order of the elements in the entire ArrayList.
Contains Checks whether specified element exists in the ArrayList or not. Returns true if exists otherwise false.
Clear Removes all the elements in ArrayList.
CopyTo Copies all the elements or range of elements to compitible Array.
GetRange Returns specified number of elements from specified index from ArrayList.
IndexOf Search specified element and returns zero based index if found. Returns -1 if element not found.
ToArray Returns compitible array from an ArrayList.

Adding Elements into ArrayList

The AddRange() method can take any type of collection that implements the ICollection interface e.g. List, ArrayList, SortedList, Queue, Stack, HashSet, Hashtable, etc.

Use the Add()method to add a single element or the AddRange() method to add multiple elements from the other collections into an ArrayList. Here, the element means the literal value of a primitive or non-primitive type. Please note that the AddRange() method only available in the ArrayList class but not in IList. So, it can only be use with the variable of type ArrayList.

Signature: int Add(Object value)
void AddRange(ICollection c)

Example: Adding Elements into ArrayList
ArrayList arryList1 = new ArrayList();
arryList1.Add(1);
arryList1.Add("Two");
arryList1.Add(3);
arryList1.Add(4.5);

IList arryList2 = new ArrayList()
{
    100, 200
};

//Adding entire collection using ArrayList.AdRange() method.
////Note: IList does not contain AddRange() method.
arryList1.AddRange(arryList2);

You can also add items when you initialize it using object initializer syntax.

IList arrayList = new ArrayList() { 100, "Two", 12.5, 200 };

ArrayList can contain multiple null and duplicate values.

Accessing Elements

ArrayList elements can be accessed using indexer, in the same way as an array. However, you need to cast it to the appropriate type or use the implicit type var keyword while accessing it.

Example: Accessing Elements
ArrayList myArryList = new ArrayList();
myArryList.Add(1);
myArryList.Add("Two");
myArryList.Add(3);
myArryList.Add(4.5f);

//Access individual item using indexer
int firstElement = (int) myArryList[0]; //returns 1
string secondElement = (string) myArryList[1]; //returns "Two"
int thirdElement = (int) myArryList[2]; //returns 3
float fourthElement = (float) myArryList[3]; //returns 4.5

//use var keyword
var firstElement = myArryList[0]; //returns 1

Use a foreach or a for loop to iterate an ArrayList.

Example: Iterate ArrayList
IList myArryList = new ArrayList()
                        {
                            1,
                            "Two",
                            3,
                            4.5F
                        };

foreach (var val in myArryList)
    Console.WriteLine(val); 
            
//Or
for(int i = 0 ; i< myArryList.Count; i++)
    Console.WriteLine(myArryList[i]);
Output:
1
Two
3
4.5

Inserting Elements into ArrayList

Use the IList.Insert() method to insert a single item at the specified index.

Signature: void Insert(int index, Object value)

Example: Insert()
IList myArryList = new ArrayList();
myArryList.Add(1);
myArryList.Add("Two");
myArryList.Add(3);
myArryList.Add(4.5);

myArryList.Insert(1, "Second Item");
myArryList.Insert(2, 100);

foreach (var val in myArryList)
        Console.WriteLine(val); 

Use the ArrayList.InsertRange() method to insert all the values from another collection into ArrayList at the specfied index. Please note that the InsertRange() method only available in the ArrayList class but not in IList. So, it can only be use with the variable of type ArrayList.

Signature: Void InsertRange(int index, ICollection c)

Example: InsertRange()
IList arryList1 = new ArrayList();
arryList1.Add(100);
arryList1.Add(200);

ArrayList arryList2 = new ArrayList();
arryList2.Add(10);
arryList2.Add(20);
arryList2.Add(30);

arryList2.InsertRange(2, arryList1);

foreach(var item in arryList2)
    Console.WriteLine(item);
Output:
10
20
100
200
30

Remove Elements from ArrayList

Use the IList.Remove() method to remove a specified element from an ArrayList.

Signature: void Remove(Object obj)

Example: Remove()
IList arryList1 = new ArrayList();
arryList1.Add(100);
arryList1.Add(200);
arryList1.Add(300);

arryList1.Remove(100); //Removes 1 from ArrayList

foreach (var item in arryList1)
    Console.WriteLine(item);
Output:
200
300

Use the IList.RemoveAt() method to remove an element from the specified index location.

Signature: void RemoveAt(int index)

Example: RemoveAt()
IList arryList1 = new ArrayList();
arryList1.Add(100);
arryList1.Add(200);
arryList1.Add(300);

arryList1.RemoveAt(1); //Removes the first element from an ArrayList

foreach (var item in arryList1)
    Console.WriteLine(item);
Output:
100
300

Use the ArrayList.RemoveRange() method to remove multiple elements from the specified index till the specified number of elements in the ArrayList. Please note that the RemoveRange() method only available in the ArrayList class but not in IList. So, it can only be use with the variable of type ArrayList.

Signature: void RemoveRange(int index, int count)

Example: RemoveRange()
ArrayList arryList1 = new ArrayList();
arryList1.Add(100);
arryList1.Add(200);
arryList1.Add(300);

arryList1.RemoveRange(0,2);//Removes two elements starting from 1st item (0 index)

foreach(var item in arryList1)
    Console.WriteLine(item);
Output:
300

ArrayList Sorting

The ArrayList class includes Sort() and Reverse() method. The Sort() method arranges elements in ascending order. However, all the elements should have same data type so that it can compare with default comparer otherwise it will throw runtime exception.

The Reverse() method arranges elements in reverse order. Last element at zero index and so on.

Example: Sort(), Reverse()
ArrayList arryList1 = new ArrayList();
arryList1.Add(300);
arryList1.Add(200);
arryList1.Add(100);
arryList1.Add(500);
arryList1.Add(400);

Console.WriteLine("Original Order:");

foreach(var item in arryList1)
    Console.WriteLine(item);

arryList1.Reverse();
Console.WriteLine("Reverse Order:");

foreach(var item in arryList1)
    Console.WriteLine(item);

arryList1.Sort();
Console.WriteLine("Ascending Order:");

foreach(var item in arryList1)
    Console.WriteLine(item);

Check for an Existing Elements in ArrayList

The IList.Contains() method checks whether specified element exists in the ArrayList or not. Returns true if exists otherwise false.

Example: Contains()
IList myArryList = new ArrayList();
myArryList.Add(100);
myArryList.Add("Hello World");
myArryList.Add(300);

Console.WriteLine(myArryList.Contains(100)); // true
Points to Remember :
  1. ArrayList can store items(elements) of any datatype.
  2. ArrayList resizes automatically as you add the elements.
  3. ArrayList values must be cast to appropriate data types before using it.
  4. ArrayList can contain multiple null and dulplicate items.
  5. ArrayList can be accessed using foreach or for loop or indexer.
  6. Use Add(), AddRange(), Remove(), RemoveRange(), Insert(), InsertRange(), Sort(), Reverse() methods.