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

Is it possible if we use a type key for a dictionary to restrict that type to only 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 above code, for example, I want to restrict the type to only: the base and every class that inherits from it. Can such a limitation be made?

+3


source to share


2 answers


Just create a template class that inherits from Dictionary

, like so:

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

      



Then you can use it in your code as needed:

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

        Dict.Add(new InheritedObject1(), "value1");
        Dict.Add(new InheritedObject1(), "value2");
    }

      

+8


source


Ok if you do

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

      



then only Base

its children will be used as a key (in this particular case Base

there is abstract

, so only children are applied).

+1


source







All Articles