Sunday, November 2, 2008

Attribute Usage

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:
1. Add the Attribute suffix to custom attribute classes, as shown in the following example.
Visual Basic
AllowMultiple := True)> _
Public Class ObsoleteAttribute
Inherits Attribute
' Insert code here.
End Class
C#
[AttributeUsage(AttributeTargets.All, Inherited = false,
AllowMultiple = true)]
public class ObsoleteAttribute: Attribute {}
2. Seal attribute classes whenever possible, so that classes cannot be derived from them. (This improves performance.)
3. Use positional arguments for required parameters.
4. Use named arguments for optional parameters.
5. Do not name a parameter with both named and positional arguments.
6. Provide a read-only property with the same name as each positional argument, but change the case to differentiate between them.
7. Provide a read/write property with the same name as each named argument, but change the case to differentiate between them.
Visual Basic
Public Class NameAttribute
Inherits Attribute
Public Sub New(username As String)
' Implement code here.
End Sub
Public ReadOnly Property UserName() As String
Get
Return UserName
End Get
End Property
Public Property Age() As Int32
Get
Return Age
End Get
Set (value As Int32)
Age = value
End Set
End Property
' Positional argument.
End Class
C#
public class NameAttribute: Attribute
{
public NameAttribute (string username)
{
// Implement code here.
}
public string UserName
{
get
{
return UserName;
}
}
public int Age
{
get
{
return Age;
}
set
{
Age = value;
}
}
// Positional argument.
}

No comments: