Sunday, March 1, 2009

Interesting Collections

[SerializableAttribute]
[ComVisibleAttribute(false)]
public abstract class KeyedCollection<TKey, TItem> : Collection<TItem>
Use this collection class (since being a generic abstract class, your collection class is actually a concrete class derived from the constructed version of the generic type) if each collection item also contains the key.

Basically, the motivation to create and use your derived class comes from the fact that it will be making good use of inherited OOB functionality from base for free and also that you can add custom behaviors by overriding some protected members of base.

Sort of a hybrid between IList<T> and IDictionary<TKey,TValue>.

To use this collection class,
(a) First, create a constructed KeyedCollection (for example, KeyedCollection<int,OrderItem> where OrderItem class has a unique field called OrderNumber)
(b) Derive a collection class from the constructed type (for example, SimpleOrder : KeyedCollection<int,OrderItem>)
(c) Override the protected member GetKeyForItem.

No comments: