C# Non-Generic ArrayList

A non-generic arraylist is a more flexible alternative to ordinary arrays. As with arrays, an arraylist can hold multiple values, however, they don't have to be of the same type. An arraylist also has the ability to automatically resize, making it easy to add or remove elements. The example arraylist below shows the declaration of an arraylist, with five items added to it, using the 'Add' method, a numeric ID, three strings for first name, last name and title, along with a date of birth as a date value. These values are then displayed out to the console using a 'foreach' loop

ArrayList person = new ArrayList();

person.Add(1);
person.Add("Bob");
person.Add("Smith");
person.Add("Mr");
person.Add(new DateTime(1980, 1, 10));

foreach (var item in person)
{
    Console.WriteLine(item);
}

The output to the console is as follows. The items are displayed in the order that they were added to the arraylist.

1
Bob
Smith
Mr
10/01/1980 00:00:00

The declaration and initialisation of the arraylist can be done more efficiently by combining the two, whilst still allowing the ‘foreach’ loop to process the arraylist in the same way.

ArrayList person = new ArrayList()
{
    1,
    "Bob",
    "Smith",
    "Mr",
    new DateTime(1980, 1, 10)
};

Note that, like with an ordinary array, an ordinary ‘for’ loop could be used, but a ‘foreach’ loop is simpler.

As with ordinary arrays, each element in an arraylist has an index value, which starts at zero for the first element. This can be used to access individual elements of an arraylist. Here the second element with an index value of one is displayed in the console.

Console.WriteLine(person[1]);

If it is necessary to add an item into an arraylist at a specific index position, this is possible using the 'Insert' method. The index position increases by one for all subsequent elements.

person.Insert(2, "George");

In order to check if a value exists within an arraylist, the 'Contains' method can be used. This returns a Boolean true or false value. This value is displayed out to the console in the below example, however, a more common use would be in 'if' statements.

Console.WriteLine(person.Contains("Bob"));

As well as adding and inserting values, the index value can also be used to remove a specific element.

person.RemoveAt(2);

To clear an arraylist completely, the 'Clear' method can be used.

person.Clear();

Further Reading