Reputation:
I'd like to pass a Type
parameter into a constructor. This constructor belongs to an attribute.
That's simple. But how do I constrain this Type
parameter to sub classes of a particular class only?
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'll throw an exception if the type isn't a ParentClass
- but runtime is too late.
Is it possible to add some sort of constraint? Can I use generics here or am I right in saying generics are out of bounds since it's the constructor of an attribute?
Note usage:
public enum MyEnum
{
[AssociatedType(typeof(MyChildClass))]
MyEnumValue,
[AssociatedType(typeof(MyOtherChildClass))]
MyOtherEnumValue
}
Upvotes: 3
Views: 124
Reputation: 32740
You can't do this with Type
and you can't 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 ignoring the attribute if the target doesn't match the intended one.
Upvotes: 1