// creating an empty ArrayList ArrayList list = new ArrayList(); // adding elements to the ArrayList list.Add("apple"); list.Add("pear"); list.Add("orange"); list.Add("banana"); // accessing elements using indexing Console.WriteLine(list[0]); // output: apple // removing elements list.RemoveAt(1); // checking if an element exists bool containsPear = list.Contains("pear"); // containsPear = false
// creating an ArrayList with initial elements ArrayList numbers = new ArrayList() { 1, 2, 3, 4, 5 }; // iterating over the ArrayList using a foreach loop foreach (var number in numbers) { Console.WriteLine(number); }
// creating an ArrayList with elements of different types ArrayList mixedList = new ArrayList() { "hello", 42, true }; // checking the type of an element using the is keyword foreach (var item in mixedList) { if (item is string) { Console.WriteLine($"{item} is a string"); } else if (item is int) { Console.WriteLine($"{item} is an int"); } else if (item is bool) { Console.WriteLine($"{item} is a bool"); } }The ArrayList class is included in the .NET Framework Class Library, which is a collection of pre-built code that developers can use to quickly and easily add functionality to their own applications.