Search code examples
c#.netreflectioncustom-attributessystem.reflection

Can an attribute require inheritance or implementation of a class or interface?


When attempting to apply the System.AttributeUsage attribute to a class, Visual Studio will show the error "Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute". Is it possible to specify such a requirement for a custom attribute?

Imagine an attribute class CommandAttribute, which would specify the name of a command. It should only be present on classes which implement ICommand so that we can guarantee that methods like ExecuteCommand(...) exist on the class.

I can of course use reflection to check that the applied classes implement the interface at run time, but ideally we could enforce this at compile time.


Solution

  • Unfortunately, this is not directly supported by the C# language.

    However, you can write your own code analysis rule using the .NET Compiler Platform (aka Roslyn) and enforce that condition yourself.