C# ArrayList
The ArrayList
class is part of the System.Collections namespace and provides a dynamic array that can grow or shrink in size during runtime.
It is considered one of the older collections in C# and has been largely superseded by the generic collections introduced in .NET Framework 2.0, such as List<T>
.
Example of a ArrayList in C#.
using System;
using System.Collections;
class Program
{
static void Main()
{
// Creating an ArrayList
ArrayList arrayList = new ArrayList();
// Adding elements to the ArrayList
arrayList.Add(10);
arrayList.Add("Hello");
arrayList.Add(3.14);
// Accessing elements in the ArrayList
Console.WriteLine("Elements in the ArrayList:");
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
// Removing an element from the ArrayList
arrayList.Remove("Hello");
Console.WriteLine("\nAfter removing 'Hello':");
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
}
}
ArrayList
stores objects, so elements of different types can be added.
However, this flexibility comes with a trade-off: you lose type safety, and you may need to perform explicit type casting when retrieving elements.
It's generally recommended to use the generic collections like List<T>
instead of ArrayList
when working with collections in modern C# code, as they provide type safety and improved performance.