Restricting Type Parameters in Method / Constructor

I would like to pass a parameter Type

to the constructor. This constructor belongs to the attribute.

It's simple. But how do I restrict this parameter to Type

only subclasses of a certain class?

So, I have a parent class ParentClass

and two child classes MyChildClass : ParentClass

and MyOtherChildClass : ParentClass

.

My attribute looks like this:

public class AssociatedTypeAttribute : Attribute
{
    private readonly Type _associatedType;

    public Type AssociatedType => _associatedType;

    public AssociatedTypeAttribute(Type associatedType)
    {
        if (!associatedType.IsSubclassOf(typeof(ParentClass)))
            throw new ArgumentException($"Specified type must be a {nameof(Parentclass)}, {associatedType.Name} is not.");

        _associatedType = associatedType;
    }
}

      

This works and at runtime it throws an exception if the type is not ParentClass

, but the runtime is too long.

Can I add some kind of restriction? Can I use generics here, or am I right in saying that generics are out of scope since this is an attribute constructor?

Note:

public enum MyEnum
{
   [AssociatedType(typeof(MyChildClass))]
   MyEnumValue,
   [AssociatedType(typeof(MyOtherChildClass))]
   MyOtherEnumValue
}

      

+3


source to share


1 answer


You cannot do it with Type

, and you cannot use generics because it is not allowed to extend Attribute

with a generic class.



The best solution you have is a runtime check and simply ignore the attribute if the target is not what you intended.

+1


source







All Articles