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
AttributeUsagealone, but can be achieved in other way.AttributeUsagehasValidOnproperty, that is ofAttributeTargettype. It lets you specify that it's valid only onclass, but not type of this class.So, why
AttributeUsageonly works on classes that derive fromAttribute? It's a compiler rule CS0641It's not part of
AttributeUsageitself.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-analyzerscode,CS0641is 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!