In C# there is a attribute called AttributeUsage
, if you want to set this attribute to a class it automatically detects if the class is derived from the Attribute class and if not it will throw an error.
How can I create such restrictions?
I want to create an attribute which should only be available/settable on a specific class.
What you are trying to do is not possible via attributes
AttributeUsage
alone, but can be achieved in other way.AttributeUsage
hasValidOn
property, that is ofAttributeTarget
type. It lets you specify that it's valid only onclass
, but not type of this class.So, why
AttributeUsage
only works on classes that derive fromAttribute
? It's a compiler rule CS0641It's not part of
AttributeUsage
itself.If you want to achieve something like this, you will need to write your own Roslyn analyzer, that will check it for you. There are few tutorials on how to do write one, i.e. official one or this), I also suggest to look at
roslyn-analyzers
code,CS0641
is not there, since it's a compiler error, not an analyzer, but you can get quite a lot of references here.I hope it helps you, wish you good luck!