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.Redto the target class or interfaceA 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 {} ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access