What I want is a unique collection, or set, of objects referenced by their class. This set can only contain one object of a given class. Here is an example of some possible functionality:
class A;
class B;
class C;
A a = new A();
B b = new B();
C c = new C();
UnknownCollection<object> objects;
objects.Add(A, a); // Add(key, value)
objects.Add(B, b);
objects.Add(C, c);
var something = objects[A]; // return a reference to 'a' using class A as a key
If something along these lines doesn’t already exist, might there be a way to create one with reasonable performance?
It sounds like you really want a
Dictionary<Type, object>which you populate with:If the dictionary always maps a type to an instance of that type, you can encapsulate that so you can keep the API clean. You always know the cast will work, because the only code which can add to the dictionary ensures that the type is always correct.
EDIT: Aha – it turns out I blogged about this back in 2008.