Mama Tate
Mama Tate

Reputation: 283

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?

Upvotes: 4

Views: 6719

Answers (2)

dav_i
dav_i

Reputation: 28097

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).

Upvotes: 1

Martin
Martin

Reputation: 16423

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");
    }

Upvotes: 8

Related Questions