2.11 Create a Strongly Typed Collection


Problem

You need to create a collection that can hold elements only of a specific type.

Solution

Create a class that derives from the System.Collections.CollectionBase or System.Collections.DictionaryBase classes, and implement type-safe methods for the manipulation of the collection.

Discussion

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 methodssuch as OnClear , OnClearComplete , OnGet , OnGetComplete , and so onare 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.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net