Export (0) Print
Expand All

How to: Provide Metadata Descriptions About Your Component

You can provide descriptive metadata about your component through attributes. Attributes are specialized classes that are applied to code elements. At compile time, attributes are emitted into metadata that is available to the common language runtime or to custom tools and applications through the System.Reflection namespace.

Attributes are attached to a component by preceding the component with a reference to the attribute and providing any relevant parameters or flags. This call to the constructor is placed within angle brackets <> in Visual Basic and regular brackets [] in C#.

By convention, all attribute classes end in "Attribute." For example, there are DescriptionAttribute, ObsoleteAttribute, and BrowsableAttribute classes. However, several languages that target the common language runtime, including Visual Basic and C#, do not require the full name of the attribute. For example, the ObsoleteAttribute may be referred to in code as Obsolete.

To attach an existing attribute to your component

  1. Determine which attributes are required for your component.

  2. Attach the attributes to your component. Note that you must either use the fully qualified name of the attribute or add the appropriate Imports (using) statement. The following example shows how to attach the DescriptionAttribute attribute:

    using System.ComponentModel;
    [Description("This is a description string")]
    public class TheClass
    {
    }
    

You can also create your own attributes for use with your own custom tools or applications by inheriting from Attribute. You can add to this base class any custom properties or methods needed by your application.

To create and apply a custom attribute

  1. Create a class that inherits from Attribute.

    public class WidgetAttribute: System.Attribute
    {
    }
    
  2. Determine which properties and methods your attribute needs and write the code for them. The following example shows how to create a WidgetType property that is set in the constructor of the WidgetAttribute class. TheAttributeUsageAttribute attribute sets what code members the attribute can target.

    [AttributeUsage(System.AttributeTargets.Class)]
    public class WidgetAttribute: System.Attribute
    {
       private WidgetTypeEnum widgetType;
    
       // Creates a readonly property for the WidgetAttribute class.
       public WidgetTypeEnum WidgetType
          {
             get {return widgetType;}
          }
    
       public WidgetAttribute(WidgetTypeEnum type): base()
          {
             widgetType = type;
          }
    }
    
  3. Apply this attribute as you would any other attribute, being certain to apply any needed parameters.

    [WidgetAttribute(WidgetTypeEnum.VerticalWidget)]
    public class WidgetFortyFive
    {
    }
    
Show:
© 2014 Microsoft