Attribute Usage Guidelines
The .NET Framework enables developers to invent new kinds of declarative information, to specify declarative information for various program entities, and to retrieve attribute information in a run-time environment. For example, a framework might define a HelpAttribute attribute that can be placed on program elements such as classes and methods to provide a mapping from program elements to their documentation. New kinds of declarative information are defined through the declaration of attribute classes, which might have positional and named parameters. For more information about attributes, see Writing Custom Attributes.
The following rules outline the usage guidelines for attribute classes:
Add the
Attribute
suffix to custom attribute classes, as shown in the following example.Public Class ObsoleteAttribute{} [C#] public class ObsoleteAttribute{}
Specify
AttributeUsage
on your attributes to define their usage precisely, as shown in the following example.<AttributeUsage(AttributeTargets.All, Inherited := False, AllowMultiple := True)> _ Public Class ObsoleteAttribute Inherits Attribute ' Insert code here. End Class [C#] [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] public class ObsoleteAttribute: Attribute {}
Seal attribute classes whenever possible, so that classes cannot be derived from them.
Use positional arguments (constructor parameters) for required parameters. Provide a read-only property with the same name as each positional argument, but change the case to differentiate between them. This allows access to the argument at runtime.
Use named arguments (read/write properties) for optional parameters. Provide a read/write property with the same name as each named argument, but change the case to differentiate between them.
Do not define a parameter with both named and positional arguments. The following example illustrates this pattern.
Public Class NameAttribute Inherits Attribute ' This is a positional argument. Public Sub New(username As String) ' Implement code here. End Sub Public ReadOnly Property UserName() As String Get Return UserName End Get End Property ' This is a named argument. Public Property Age() As Integer Get Return Age End Get Set Age = value End Set End Property End Class [C#] public class NameAttribute: Attribute { // This is a positional argument. public NameAttribute (string username) { // Implement code here. } public string UserName { get { return UserName; } } // This is a named argument. public int Age { get { return Age; } set { Age = value; } } }
See Also
Design Guidelines for Class Library Developers | Attribute Naming Guidelines