Search code examples
c#.netattributesattributeusage

How to create attribute with class restrictions


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.


Solution

  • What you are trying to do is not possible via attributes AttributeUsage alone, but can be achieved in other way.

    AttributeUsage has ValidOn property, that is of AttributeTarget type. It lets you specify that it's valid only on class, but not type of this class.

    So, why AttributeUsage only works on classes that derive from Attribute? It's a compiler rule CS0641

    'attribute' : attribute is only valid on classes derived from System.Attribute

    An attribute was used that can only be used on a class that derives from System.Attribute.

    It'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!