Defining a Custom Attribute
An
attribute
is merely a class that inherits from System.Attribute, which makes it
very easy to implement a custom attribute. In this section,
we’ll build a custom attribute called
<DeveloperNote>, which allows a developer to
add assorted information (the developer’s name, the
date, a comment, and whether a code modification was a response to a
bug) to code. The steps are as follows:
Define a public class that inherits from System.Attribute or another attribute class derived from System.Attribute. For example:
Public Class DeveloperNoteAttribute Inherits System.Attribute
Note that, by convention, the name of the class ends with the substring “Attribute”.
Apply the
<AttributeUsage>attribute, which defines the language elements to which the custom attribute can be applied, to the class (as shown in the following code fragment). The attribute’s only required argument is one of the following members of theAttributeTargetsenumeration:AllAssemblyClassConstructorDelegateEnumEventFieldInterfaceMethodModuleParameterPropertyReturnValueStructIf an attribute applies to multiple programming elements, but not all elements, the relevant constants can be
ORed together. In the case of our<DeveloperNote>attribute, we want the attribute to apply to all program elements. In addition, we want to make the<DeveloperNote>attribute extensible through inheritance, so we set the<AttributeTarget>attribute’sInheritedargument toTrue. Finally, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access