Skip to content

Instantly share code, notes, and snippets.

@atrauzzi
Last active January 2, 2016 03:19
Show Gist options
  • Save atrauzzi/8242870 to your computer and use it in GitHub Desktop.
Save atrauzzi/8242870 to your computer and use it in GitHub Desktop.
// http://stackoverflow.com/questions/20907068/how-to-create-a-strongly-typed-collection-that-only-contains-one-element-per-typ
class TypedSet<AbstractType> {
protected Dictionary<Type, AbstractType> data;
public TypedSet() {
data = new Dictionary<Type, AbstractType>();
}
public void Add(AbstractType subclassOfAbstract) {
data.Add(subclassOfAbstract.GetType(), subclassOfAbstract);
}
public ConcreteType Get<ConcreteType>() where ConcreteType : AbstractType {
return (ConcreteType)GetByType(typeof(ConcreteType));
}
public bool Has<ConcreteType>() where ConcreteType : AbstractType {
return data.ContainsKey(typeof(ConcreteType));
}
protected AbstractType GetByType(Type type) {
return data[type];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment