Home > Net >  Forcing IDictionary key to be within specific class type
Forcing IDictionary key to be within specific class type

Time:12-27

I have the following member variable:

private IDictionary<Type, int> foo = ...

The keys must be of BaseClass, SubClass1, or SubClass2. E.g. of insertion:

foo.Add(typeof(BaseClass), ...);
foo.Add(typeof(SubClass1), ...);
foo.Add(typeof(SubClass2), ...);

Any classes not from the same hierarchy should not be allowed to be added.

Is it possible to achieve that?

CodePudding user response:

Yes, you can do this by using a generic type parameter and specifying a constraint on that type parameter.

private IDictionary<Type, int> foo = ...

public void Add<T>(T key, int value) where T : BaseClass
{
    foo.Add(typeof(T), value);
}

Any classes which are not derived from BaseClass will not be allowed because of the where T : BaseClass constraint.

There is another way to do this by checking the type while adding to the dictionary.

public void Add(Type key, int value)
{
    if (key.IsSubclassOf(typeof(BaseClass)))
    {
        foo.Add(key, value);
    }
  •  Tags:  
  • c#
  • Related