I need to declare a Dictionary having a Type as key and an instance as value.
I need to limit key Type to a certain class hierarchy.
For a Java Map, I can do something like:
Map<Class<? extends MySuperClass>, ? extends MySuperClass>
How can I achieve this in C#?
Do not expose Dictionary directly, this way you can control manually when to add
public void AddToDictionary(Type key, object value)
{
if(!key.IsAssignableFrom(typeof(SomeBaseClass))
throw new ArgumentException("Must be an inherited from SomeBaseClass type");
dictionary.Add(key, value);
}
I think Sinatr's approach of exposing a method for adding to the dictionary instead of the dictionary itself is a very good idea. The only downside is that you get no compile time safety; if some code added an object of the wrong type you wouldn't find out till runtime.
Using generics, however, we can tweak the method so that adding objects is foolproof:
public void AddToDictionary<T>(T value) where T: MySuperClass
{
dict.Add(typeof(T), value);
}
Now it is impossible to write a program that adds objects of the wrong type and still compiles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With