Subscribe

RSS Feed (xml)

Create a Strongly Typed Collection

The CollectionBase and DictionaryBase classes provide convenient base classes from which to derive type-safe collections without having to implement the standard IDictionary, IList, ICollection, and IEnumerable interfaces from scratch.
CollectionBase is for IList-based collections (such as ArrayList). Internally, CollectionBase maintains the collection using a standard ArrayList object, which is accessible through the protected property List. DictionaryBase is for IDictionary-based collections (such as Hashtable). Internally, DictionaryBase maintains the collection using a standard Hashtable object, which is accessible through the protected property Dictionary. The following code shows the implementation of a strongly typed collection (based on the CollectionBase class) to represent a list of System.Reflection.AssemblyName objects.
using System.Reflection;
using System.Collections;

public class AssemblyNameList : CollectionBase {

    public int Add(AssemblyName value) {

        return this.List.Add(value);
    }

    public void Remove(AssemblyName value) {

        this.List.Remove(value);
    }

    public AssemblyName this[int index] { 

        get {
            return (AssemblyName)this.List[index];
        }

        set {
            this.List[index] = value;
        }
    }

    public bool Contains(AssemblyName value) {

        return this.List.Contains(value);
    }

    public void Insert(int index, AssemblyName value) {

        this.List.Insert(index, value);
    }
}
Both the CollectionBase and DictionaryBase classes implement a set of protected methods with the prefix On*. These methods—such as OnClear, OnClearComplete, OnGet, OnGetComplete, and so on—are intended to be overridden by a derived class and allow you to implement any custom functionality necessary to manage the strongly typed collection. The CollectionBase and DictionaryBase classes call the appropriate method before and after modifications are made to the underlying collection through the List or Dictionary properties.

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail