The ArrayList class permits you to store values of various information varieties and additionally offers you the power to feature and take away components any time you would like. the subsequent examples show a straightforward practicality of the ArrayList class.

using System;
using System.Collections;
 
namespace ArrayListDemo
{
    public class Program
    {
        public static void Main()
        {
            ArrayList myArray = new ArrayList(); 
 
            myArray.Add("John"); 
            myArray.Add(5);      
            myArray.Add(true);   
            myArray.Add(3.65);   
            myArray.Add('R');    
 
            foreach (object element in myArray)
            {
                Console.WriteLine(element.ToString());
            }
        }
    }
}

Example 1 – ArrayList Demo

John
5
true
3.65
R

To be able to use the ArrayList class, you must import System.Collections namespace. We created a new instance of the ArrayList class. To add new elements to the array, the Add method was used. It accepts an argument of type object therefore, you can pass any type of values to it since everything inherits object in C#. We then add five values of different data types to show the ability of the ArrayList class to hold different types of values. We then read each of the values using a foreach loop. Since the ArrayList class has different data types, we cannot use a specific data type for the variable that will hold each of this values inside the for loop. We used object instead so every element can be stored. Inside the loop, we used the ToString() method to show the values.

Note that you can also access each elements using their index just like normal arrays. For example, the code below uses a for loop to read each element.

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

Note the use of the Count property. The Count property is like the Length property of an ordinary array. It counts the number of elements of the ArrayList object. We accessed each element using their index.

Another thing to note is that you can give an initial capacity for the ArrayList class. For example, you can indicate that the ArrayList object can have five elements using an overloaded constructor.

ArrayList myArray = new ArrayList(5);

Those five slots will have empty values unless you use the Add method to add new ones. If the slots are full and you add another one, the size of the ArrayList object will be adjusted accordingly. You can resize the size of the capacity of the   ArrayList object by changing the value of the Capacity property.

Another version of the ArrayList class’ constructor is the one that accepts an object that implements ICollection interfaces. The System.Array is an example of that object. Therefore, you can pass an array to the constructor and the values of that array will be copied to the ArrayList object.

object[] array = {"John", 5, true, 3.65, 'R' };

ArrayList myArray = new ArrayList(array);

You can use the Remove method of the ArrayList category to get rid of parts. The Remove method accepts associate degree object that matches the worth of a component in associate degree array. it’ll take away the primary incidence of the part that has that worth. If you take away a component that’s not within the last position, any part following it’ll regulate their position in order that the empty position that the removed part was accustomed be are going to be occupied. this is often incontestable by the subsequent code.

using System;
using System.Collections;
 
namespace ArrayListDemo2
{
    public class Program
    {
        public static void Main()
        {
            ArrayList myArray = new ArrayList();
 
            myArray.Add("John");
            myArray.Add(5);
            myArray.Add(true);
            myArray.Add(3.65);
            myArray.Add('R');
 
            for (int i = 0; i < myArray.Count; i++)
            {
                Console.WriteLine("myArray[{0}] = {1}", i, myArray[i]);
            }
 
            //Remove element number 1
            myArray.Remove(5);
 
            Console.WriteLine("\nAfter removing myArray[1] (The value 5)...\n");
 
            for (int i = 0; i < myArray.Count; i++)
            {
                Console.WriteLine("myArray[{0}] = {1}", i, myArray[i]);
            }
        }
    }
}

Example 2 – Using the Remove() Method

myArray[0] = John
myArray[1] = 5
myArray[2] = True
myArray[3] = 3.65
myArray[4] = R

After removing myArray[1] (The value 5)...

myArray[0] = John
myArray[1] = True
myArray[2] = 3.65
myArray[3] = R

Since we removed the value inside myArray[1], all the succeeding elements will adjust their positions. So myArray[2] will now be myArray[1]myArray[3] will be myArray[2] and so on. You can also specify the index of the element you wish to remove by using the RemoveAt method. It has one parameter which is the index of the element you are removing in the array.

Adding and Removing Multiple Items


You can add or remove multiple items at the same time using the AddRange and RemoveRange methods. Add range can accept an array of values and add those values to the ArrayList object.

ArrayList myArray = new ArrayList();

myArray.Add(1);
myArray.Add(2);

int[] numbers = { 3, 4, 5 };

myArray.AddRange(numbers);

foreach(object element in myArray)
{
    Console.WriteLine(element);
}
1
2
3
4
5

The RemoveRange method is quite different compared to AddRange. It accepts two int parameters, the index of the starting element and the number of elements to remove. For example, if you want to remove elements 2 to 6, you can use the following code:

myArray.RemoveRange(2, 5);

Searching for Values


You can check if a particular value is inside the list by using Contains() method. It accepts an object argument and returns true if that value is found inside the list of elements. You can also use the IndexOf() and LastIndexOf() methods to determine the index of a certain value. The IndexOf() method returns the index of the first occurrence of a given value. The LastIndexOf() returns the index of the last occurrence of the value. They will both return -1 if the value was not found within the list of elements. You can also use the BinarySearch method that also accepts the value to be searched. The BinarySearch() method is suitable if you are searching a value within a very long list of elements.

Sorting ArrayList Values


You can use the Sort() method to sort the elements in the array. Numbers are sorted from lowest to highest, while strings and characters are arranged alphabetically. If you use this method, all the elements should be comparable. For example, you cannot mix up a string and an int inside the ArrayList and then use the Sort() method. You will learn in a later chapter that you can also use a comparer to customize the way the Sort() method sorts elements.