I'm in the process of trying to create a collection that will only contain one element per type. Each of the types will have to subclass a root type however, so that there is a commonality. I've done some research and am wondering if I'm on the right track here or if there are some improvements that can be made:
class TypedList<T> : Dictionary<Type, T> {
public override void Add<C>(T instanceOfType) {
base.Add(typeof(C), instanceOfType);
}
}
Specific questions:
- Is this the correct/best approach?
- What should I do to facilitate retrieving elements?
- If the Add() method is correct, is there any way to enforce that C is a subclass of T?
Updated code to reflect Ondrej's suggestions:
class TypedList<Abstract> : IList<Abstract> {
protected Dictionary<Type, Abstract> data;
public void TypedList() {
data = new Dictionary<Type, Abstract>();
}
public void Add<Concrete>(Concrete instanceOfType) where Concrete : Abstract {
data.Add(typeof(Concrete), instanceOfType);
}
}
Many months later and I think I've come up with a really nice solution, which is to use a collection I wasn't aware of initially
KeyedCollection
:Very conscice and doesn't require any stitching of different types of collection classes together. Makes for slightly more idiomatic code as well as
KeyedCollection
is abstract and requires implementation ofGetKeyForItem
.