• No results found

D ATA COLLECTION CLASSES

Reusable libraries

5.1 C# CLASSES AND INTERFACES

5.1.2 D ATA COLLECTION CLASSES

Looking over the interfaces in the table, the IList interface seems particularly

appropriate for the task at hand. This allows elements to be added and removed from the collection, and supports array-style indexing. Some of the data collection classes in the .NET Framework are shown in the following table. Note, in particular, those classes in the table that support the IList interface.

Interfaces related to data collections

Interface Description Sample Members

IEnumerable

Interface that supports the creation of an enumerator class for iterating over the elements in a collection.

Usage

Supporting this interface allows the C#

foreachstatement to be used with instances of a class or structure.

GetEnumerator method, which returns a class that supports the IEnumerator

interface.

IEnumerator

Interface for stepping through the elements in a collection.

Current property, to retrieve the current element from the collection.

MoveNext method, which advances to the next element in the collection.

Reset method, which sets the

enumerator just before the first element.

ICollection

An IEnumerable interface that provides sizing and synchronization capabilities. This interface is the basis for all collections in the .NET Framework.

Count property, to retrieve the number of elements in the collection.

SyncRoot property, to retrieve an object for synchronizing multi-threaded access to the collection.

CopyTo method, which copies the elements in the collection into an Array

object.

IList

An ICollection interface that provides indexing of its elements. Usage

Supporting this interface allows a class or structure to be treated as an array. This permits objects to be used as targets of data bound controls, as discussed in chapter 17.

Item property, to support array-style indexing of elements using [brackets], much like a [] override in C++.

Add method, which adds a new element to the collection.

Contains method, which determines if the collection contains a specific object.

Remove method, to remove the element from the collection at a given index value.

Since we do not have a database here, the DataView class is not appropriate. If all we

wanted was a collection of file names, the StringCollection class would work,

but then our PhotoAlbum would not be very extensible. This leaves us with a simple

array or the ArrayList or CollectionBase classes. A simple fixed-size array is

not appropriate since we would like our album to grow dynamically. So we are left to choose between the ArrayList and CollectionBase classes.

Either class would work here, and both classes can be quite useful. An overview of the ArrayList class is shown in .NET Table 5.1. Deriving our PhotoAlbum class

from ArrayList would look like this:

// Deriving PhotoAlbum from ArrayList (not our approach) public class PhotoAlbum : System.Collections.ArrayList {

// Inherits all properties and methods from ArrayList }

An advantage of this approach is that we would not need to implement many of the methods, since they would be directly inherited from ArrayList. A disadvantage is

that all methods would accept any object, and not just our Photograph objects. If

you look at the documentation, you will see that the methods in ArrayList operate

on object instances. For example, the PhotoAlbum.Add method would have the

following signature:

Some .NET classes related to data collections

Class Description Interfaces supported

Array The base class for all array objects. This class is abstract.

ICloneable, IList, ICollec- tion, IEnumerable

ArrayList A dynamically-sized array. ICloneable, IList,

ICollection, IEnumerable

CollectionBase An abstract class for creating a strongly typed collection.

IList, ICollection, IEnumera- ble

DataView A customized view of a database table.

IList,ICollection, IEnumerable, and others

Hashtable A collection of values stored based on a hash code of the value, called a key.

ICloneable, ICollection,

IEnumerable, IDictionary, and others

Queue A FIFO queue; a first in, first out collection of objects.

ICloneable, ICollection,

IEnumerable

SortedList A sorted collection of keys and values accessible by both key and index.

ICloneable, ICollection,

IEnumerable, IDictionary

StringCollection A collection of string objects. IList, ICollection,

IEnumerable

Stack A LIFO queue; a last in, first out collection of objects.

ICloneable, ICollection,

C# CLASSESANDINTERFACES 131

// PhotoAlbum.Add when derived from ArrayList public int Add( object value );

So while this would be a very easy implementation, the methods in our PhotoAlbum

class would not be type-safe, and therefore not so robust.

Let’s instead take a look at the CollectionBase class. An overview of this class is

shown in .NET Table 5.2. This class is an abstract class, and requires derived classes to implement the additional methods required to support the appropriate interfaces. This requires a little more work on our part, but creates a nicer interface that works with Photograph objects directly.

Before we create our implementation, note that an alternative implementation would incorporate a private ArrayList object in a class derived directly from Sys- tem.Object. This alternative would look something like the following:

// PhotoAlbum implementation with private ArrayList (not our approach) class PhotoAlbum

{

// internal (not inherited) ArrayList .NET Table 5.1 ArrayList class

The ArrayListclass is a collection of indexed objects where the number of objects can change dynamically. This class is part of the System.Collectionsnamespace, and is very similar to the Array class for fixed-length collections of objects. The ArrayList class sup- ports the ICloneable, IEnumerable, ICollection,and IList interfaces.

Public Properties

Capacity Gets or sets the maximum number of objects the list can contain. Count Gets or sets the actual number of objects in the array.

Public Methods

Add Adds an object to the end of the array.

AddRange Adds the elements from an ICollection interface to the end of the array.

Clear Removes all objects from the array.

Contains Determines if an object is in the array. Comparison is done using the Object.Equals method.

CopyTo Copies the ArrayList, or a portion of it, into a one-dimensional

Array object.

IndexOf Returns the zero-based index of the first occurrence of the given object in the array, or –1 if the object is not found. Comparison is done using the Object.Equals method.

Remove Removes an object from the array.

RemoveAt Removes the object at a given index from the array. Sort Sorts the array, using an IComparable interface to compare

objects.

private ArrayList _photoArray; // Constructor and other wrappers // Custom Add wrapper

public int Add(Photograph photo) {

return _photoArray.Add(photo); }

}

This would work just fine and be similar to our actual implementation derived from

CollectionBase. Our implementation is more appropriate than this alternative,

since the CollectionBase class is designed for just this purpose, and does in fact

provide access to an ArrayList member through a protected property.

.NET Table 5.2 CollectionBase class

The CollectionBaseclass is an abstract class for creating strongly typed collections. A class is strongly typed if it only allows a specific type or types in its methods, rather than a generic type such as an object. Strongly typed classes allow the compiler to ensure that the proper objects are passed to methods in the class, and can prevent errors that would other- wise occur only at runtime.

The CollectionBase class is part of the System.Collectionsnamespace. It supports the IEnumerable, ICollection,and IList interfaces. A complete list of the public mem- bers defined by this class is as follows. Derived classes must implement the additional meth- ods to support the required interfaces.

Public Properties

Count Gets or sets the actual number of objects in the array.

Public Methods

Clear Removes all objects from the array.

GetEnumerator Returns an enumerator that can iterate through the elements in the collection using the IEnumerator

interface.

RemoveAt Removes the object at a given index from the array.

Protected Properties

InnerList Gets an ArrayList instance representing the collection instance. This can be used when implementing derived classes to modify the collection.

List Gets an IList instance representing the collection instance. This can be used when implementing derived classes to modify the collection.

Protected Methods

OnClear Performs additional custom processing before clearing the contents of the collection. This can be used by derived classes to perform any required actions before the collection is cleared.

OnInsert Performs additional custom processing before inserting an element into a collection. A number of other protected methods are provided, with a similar purpose.

CLASSLIBRARIES 133