Thursday, April 14, 2005

Creating custom attributes for metadata

Do you want to create custom attributes for describing your functions and classes when developing .NET projects?

First of all, create an attribute class, derived from System.Attribute. Now, I'll create an attribute class named DescriptionAttribute. Mark it with AttributeUsageAttribute (it is a system provided attribute), to show that this class can be used as an attribute.

<AttributeUsageAttribute(AttributeTargets.Class)> _
Public Class DescriptionAttribute
Inherits System.Attribute
Public Description As String = ""
Public Sub New(ByVal MemberDescription As String)
'Whether we show this object type/method in the schema
Description = MemberDescription
End Sub
End Class

AttributeTargets.Class means, only classes can be marked with this attribute. Now, let us apply our above attribute to another class

<DescriptionAttribute("Cool Class")> _
Public Class MyClass
End Class

The string "cool class" will be passed to the constructor of your above class. That is it. Now, you may need to check a class to know whether your DescriptionAttribute is applied on it. In my next example, I'll show how to read back your custom attributes from a data type (class, functions etc) in a library.

No comments:

Articles - Design Patterns, Neural Networks, C#, Programming