How to convert Array and ArrayList in C#


ArrayList is a non-generic collection, it can store objects of any type. Array can only store objects of a specific type, the type of the array must be specified at the time of declaration.

The Main difference between an ArrayList and an Array is that we can use the ArrayList to store elements of different data types and it can re-size when elements are added dynamically.

Convert Array to ArrayList

The following example demonstrates how to convert an Array to ArrayList.

    public class ArrayToArrayListSample
    {
        public static void Main()
        {
            // Array of ints.
            int[] arrayOfInts = new int[] { 10, 3, 33, 20, 56 };
        
            // Initialize array list.
            ArrayList arrayListOfInts = new ArrayList();
        
            // Add the items to array list.
            arrayListOfInts.AddRange(arrayOfInts);
        
            // Iterate and print the items in the array list.
            foreach (int obj in arrayOfInts)
            {
                Console.WriteLine(obj);
            }
        }
    }

In the above example, we declared and initialized an integer array. To convert this array to ArrayList, we created ArrayList object and called AddRange method on the ArrayList object, passing the integer array as an argument. AddRange methods add a range of values to the underlying object.

Convert ArrayList to Array

The following example demonstrates how we can convert an ArrayList to Array.

    public class ArrayListToArray
    {
        public static void Main()
        {
            // Array List of different types of objects.
            ArrayList arrayListObjects = new ArrayList() { 10, "hello", 20 };
        
            // Convert to object array using ToArray of array list.
            object[] arrayObjects = arrayListObjects.ToArray();
        
            // Iterate and print the object array
            foreach (object obj in arrayObjects)
            {
                Console.WriteLine(obj);
            }
        
            // Array List of different types of objects.
            ArrayList arrayListInts = new ArrayList() { 10, 15, 20 };
        
            // Convert to int array using ToArray of array list.
            int[] arrayInts = arrayListInts.ToArray(typeof(int)) as int[];
        
            // Iterate and print the object array
            foreach (int obj in arrayInts)
            {
                Console.WriteLine(obj);
            }
        }
    }

The above example shows the usage of ToArray method of ArrayList. ToArray method is overloaded if you do not pass a Type argument it will return an array of Type object if the type is specified it will return an array of the specified type.