C# ArrayList

In C#, ArrayList is a non-generic collection class that can be used to store elements of any type in an ordered sequence. It is part of the System.Collections namespace.

To use the ArrayList class, you need to first create an instance of the class, and then add elements to it. Here is an example:

refer‮igi:ot ‬ftidea.com
using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        // Create an ArrayList and add some elements to it
        ArrayList myList = new ArrayList();
        myList.Add("apple");
        myList.Add("banana");
        myList.Add("cherry");
        
        // Print out the elements of the ArrayList
        foreach (string fruit in myList)
        {
            Console.WriteLine(fruit);
        }
        
        // Remove an element from the ArrayList
        myList.Remove("banana");
        
        // Print out the elements of the ArrayList again
        foreach (string fruit in myList)
        {
            Console.WriteLine(fruit);
        }
    }
}

In this example, we create an instance of the ArrayList class, add some elements to it using the Add method, and then print out the elements using a foreach loop. We then remove an element from the ArrayList using the Remove method, and print out the elements again.

One thing to note about the ArrayList class is that it can store elements of any type, including value types and reference types. However, when you retrieve an element from an ArrayList, it is returned as an object type, so you need to cast it to the appropriate type before using it.

Also, since ArrayList is a non-generic collection, it does not provide type safety at compile time. This means that you may get runtime errors if you try to add elements of the wrong type to the ArrayList. To avoid this, it is recommended to use the generic List<T> class instead of ArrayList where possible.