Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring generic Dictionary with bounded type

Tags:

c#

.net

generics

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#?

like image 427
davioooh Avatar asked Feb 22 '26 03:02

davioooh


2 Answers

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);
}
like image 58
Sinatr Avatar answered Feb 23 '26 15:02

Sinatr


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!