Implementing Custom Attributes

Implementing a custom attribute (and the accompanying reflection code to make use of it) is easy and straightforward. For example, suppose you want to provide a custom attribute that adds a color option to your classes and interfaces. The color is an enum defined as:

    public enum ColorOption {Red,Green,Blue};

The color attribute should also have:

  • A default constructor that assigns ColorOption.Red to the target class or interface

  • A parameterized constructor that accepts the color to assign to the target class or interface

  • A property that accepts the color to assign to the target class or interface

Example C-3 shows the implementation of the ColorAttribute class.

Example C-3. Implementing a custom attribute

public enum ColorOption {Red,Green,Blue};

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface)]
public class ColorAttribute : Attribute
{
   ColorOption m_Color;
   public ColorOption Color
   {
      get
      {
         return m_Color;
      }
      set
      {
         m_Color = value;
      }
   }
   public ColorAttribute()
   {
      Color = ColorOption.Red;
   }
   public ColorAttribute(ColorOption color)
   {
      this.Color = color;
   }
}

Before walking though Example C-3, here are a few examples that use the ColorAttribute custom attribute:

  • Using the default constructor:

    [Color]
    public class MyClass1
    {}
  • Using the parameterized constructor:

    [Color(ColorOption.Green)]
    public class MyClass2
    {}
  • Using the property:

    [Color(Color = ColorOption.Blue)]
    public class MyClass3
    {}
  • Using it on an interface:

    [Color] public interface IMyInterface {} ...

Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.