The SLAR on System.AttributeUsageAttribute
Boy, it has been a while sense I did one of these… but, never the less, continuing in the series on sharing some of the information in the .NET Framework Standard Library Annotated Reference Vol 1 here are some of the annotations on the
System.AttributeUsageAttribute class.
BTW, if you have comments (good or bad) on the book, I’d love to hear them. In addition I encourage you to post them to Amazon where other developers can benefit from them.
BA Notice that this custom attribute is sealed. In general I am not a big fan of randomly
sealing classes to prevent extensibility. (I prefer non-virtual methods for that
purpose.) However, for custom attributes it is a good practice. In the .NET Framework,
the reflection code path that looks up custom attributes from members is
slightly faster if it does not have to consider subclasses of the target attribute.
BG In general, sealing a class or making members non-virtual (when appropriate)
can help a JIT to inline methods. Inlining has always been a powerful optimization, but
virtual methods can prevent inlining. Sealing members or leaving them non-virtual also
allows you more flexibility in changing your class’s implementation in the future, by
limiting users’ points of customization. Non-virtual members definitely have an appropriate
place both as a design point and as an implementation detail for better
Performance.
Users defining their own custom attributes should specify the AttributeTarget-
Attribute at all times. Like this:
[AttributeUsage (AttributeTargets.Methods |
AttributeTargets.Properites,
AllowMultiple=false)]
public class MyNewAttribute : Attribute
{
public MyNewAttribute () {}
}
We begrudgingly added the AttributeTargetAttribute to the Attribute class
so that people subclassing Attribute didn’t need to understand another custom
attribute when creating their own custom attribute. However, this allows people
using that new attribute to put the attribute in potentially surprising places. If you
define an attribute to function as a marker on an assembly, your program might not
work as expected if you happen to find the custom attribute applied to the return
value of a method. Class library authors really need to understand and use this
attribute.