Skip to content

32. Collection Classes

February 12, 2011

Dynamic arrays: class System.Collections.ArrayList

In C#, the class ArrayList implements a “dynamic array of objects”. The size of the array is automatically adjusted, as needed, when elements are added, which is not the case with traditional arrays.

Declaration & Instanciation of an instance of class ArrayList

The class ArrayList implements the interface IList using an array whose size is dynamically increased.
Example: Insert 2 objects of type Person in a dynamic array:

Insert two Person objects in dynamic array of type arraylist

The insertion of objects from different classes is of no problem, the difficulty is when extracting the object, the object type must be known.
Removing an object from a dynamic array doesn’t mean that it will be deleted. It signifies that the instance concerned is not a part of the collection anymore. It is the Garbage Collector in C# that is responsible with the cleaning up of the object when it is no longer referenced.

The class ArrayList implements other methods, such as:

  • int LastIndexOf(object value)(+overloads)
    Equivalent to IndexOf, except the search is from the last to the first.
  • void RemoveRange(int index, int count)
    Removes a range of elements.

Same as with the arrays, one directly accesses the ith element using its index.
The operator [] is allowed for the objects of the class ArrayList.
The class ArrayList implements the interface ICollection and IEnumerable which enables it to iterate through a list with the instruction foreach:

To cycle through a dynamic array myList:

Instruction foreach iterating through all object in dynamic array

If the array contains objects of different types, use the object type:

Instruction foreach iterate through all object in the dynamic array

Happy Programming! =)


From → OOP

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: