Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary - using type as key and constraint it to only to certain types

Is it possible, if we use a Type as key for a dictionary, to constrain that type only to specific ones? For example:

public abstract class Base
{ }

public class InheritedObject1 : Base
{ }

public class InheritedObject2 : Base
{ }

public class Program
{
    public Dictionary<Type, string> myDictionary = new Dictionary<Type, string>();
}

So from the code given above for instance i want to constraint the Type only to : Base and every class which inherits from it. Is it possible to make such a constraint?

like image 899
Mama Tate Avatar asked Jan 09 '23 03:01

Mama Tate


2 Answers

Just create a template class that inherits from Dictionary, as so:

class CustomDictionary<T> : Dictionary<T, string>
    where T : Base
{
}

Then you can use it in your code as required:

    public void Test()
    {
        CustomDictionary<InheritedObject1> Dict = new CustomDictionary<InheritedObject1>();

        Dict.Add(new InheritedObject1(), "value1");
        Dict.Add(new InheritedObject1(), "value2");
    }
like image 139
Martin Avatar answered Jan 25 '23 20:01

Martin


Well if you do

public Dictionary<Base, string> myDictionary = new Dictionary<Base, string>();

then only Base and its children will be able to be used as the key (in this specific case Base is abstract so only children applies).

like image 45
dav_i Avatar answered Jan 25 '23 20:01

dav_i