Question

Let's say I have an interface IAppModule, implemented by a few classes. Is it at all possible to write a custom attribute that can only be applied to types that expose IAppModule? If so, how?

Was it helpful?

Solution

No, unfortunately it's not possible.

You can, however, when using reflection to process your attributes, check if the decorated type is a class that implements the IAppModule interface.

typeof(someType).GetInterfaces().Contains(typeof(IAppModule))

It doesn't stop users of your attribute from using it incorrectly (in any other class), but if you decide to go with this approach, I'd recommend providing very clear documentation describing how the attribute should be used and adding the layer of validation I mentioned above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top