I have a custom attribute which is applied to class properties and the class itself. Now all the classes that must apply my custom attribute are derived from a single base class.
How can I restrict my Custom Attribute so that it can be applied to only those classes, that must derive from my base class? How do I do this?
Darn, I hate it when I prove myself wrong… it works if you define the attribute as a protected nested type of the base-class:
(original answer)
You cannot do this – at least, not at compile time.
Attributes can be restricted (for exmaple) to “class”, “struct”, “method”, “field”, etc – but nothing more granular.
Of course, since attributes do nothing by themselves (ignoring PostSharp), they will be inert on other types (and inert on your types unless you add some code to look at the attributes at runtime).
You could write an FxCop rule, but that seems overkill.
I wonder, however, whether an attribute is the best choice:
If they must apply your custom attribute, maybe an
abstract(or maybe justvirtual) property / method would be a better choice?