28.5. The AttributeUsage attribute

It's about time we examined the AttributeUsage attribute in greater detail. After all, AttributeUsage is the special attribute you apply to all your attribute classes so that the C# compiler knows how you want your attribute to work.

A class that is tagged with AttributeUsage must be a subclass of System.Attribute, or else a compilation error will occur. The AttributeUsage attribute specification can take in three parameters – one positional (and hence mandatory) and two named ones:

  • AttributeTarget – an int to indicate which types and class entities this attribute class can be applied to (this parameter is mandatory [5]);

    [5] Take it that the AttributeUsageAttribute class itself has only one constructor which ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.