BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

The ArrayList Collection

The thirty-seventh part of the C# Fundamentals tutorial describes the use of the ArrayList class. This general-purpose collection class provides the ability to create and manipulate a group of related objects as if they were a variable-length array.

Creating a Synchronised ArrayList

In the earlier article where collection interfaces were discussed, the concept of a thread-safe synchronised collection was described. In order to create a thread-safe ArrayList, a synchronised wrapper collection is generated using the static Synchronized method.

ArrayList myCollection = new ArrayList(
    new string[] {"One", "Two", "Three", "Four", "Five"});

ArrayList myThreadSafe = ArrayList.Synchronized(myCollection);

Console.WriteLine(myThreadSafe.IsSynchronized);	    // Outputs "True"

Providing ArrayList Functionality to Other IList Classes

The functionality provided by the ArrayList collection class is very flexible when reading, querying and adjusting a collection's contents. Functionality such as that provided by the BinarySearch, Sort and Reverse methods is useful in many situations. However, sometimes it is not appropriate to use an ArrayList in every situation, even when this functionality may be required.

The ArrayList class includes a static method named Adapter. This creates an ArrayList wrapper for other classes that implement IList, including basic arrays. By wrapping a suitable array or collection, you can apply ArrayList functionality that is not usually available to the underlying class.

NB: Some functions of the ArrayList may cause a NotSupportedException. For example, it is not possible to add new items to an ArrayList that is a wrapper of a fixed size array.

string[] numbers = new string[] {"One", "Two", "Three", "Four", "Five"};

ArrayList wrapper = ArrayList.Adapter(numbers);

// Sort the ArrayList and underlying array
wrapper.Sort();

// List wrapper items
foreach (string s in wrapper)
{
    Console.WriteLine(s);
}

// Perform a search
Console.WriteLine("'One' found at index {0}", wrapper.BinarySearch("One"));

/* OUTPUT

Five
Four
One
Three
Two
'One' found at index 2

*/
5 May 2007