Objective
Create a string list using the ArrayList class that already exists in the .NET platform.
Once created, display all the items stored in the list. Insert a new item in the second place of the list, and then display all the items again to check if the insertion was done correctly.
Write Your C# Exercise
C# Exercise Example
// Importing the necessary namespace for using ArrayList
using System; // For basic functionalities like Console
using System.Collections; // For using the ArrayList class
class Program
{
static void Main(string[] args)
{
// Creating an ArrayList to store strings
ArrayList list = new ArrayList();
// Adding some initial items to the ArrayList
list.Add("Apple"); // Adding "Apple" to the list
list.Add("Banana"); // Adding "Banana" to the list
list.Add("Cherry"); // Adding "Cherry" to the list
// Displaying all the items in the ArrayList
Console.WriteLine("Items in the ArrayList:");
DisplayList(list);
// Inserting a new item at the second position (index 1)
list.Insert(1, "Orange"); // "Orange" will be inserted in the second place
// Displaying the items again to check if the insertion was done correctly
Console.WriteLine("\nItems after insertion:");
DisplayList(list);
}
// Helper method to display all the items in the ArrayList
static void DisplayList(ArrayList list)
{
// Looping through each item and printing it to the console
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}