CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
Building Custom Attributes
The first step in building a custom attribute is to create a new class deriving from System.Attribute.
Keeping in step with the automobile theme used throughout this book, assume you have created a brand
new C# Class Library project named AttributedCarLibrary. This assembly will define a handful of
vehicles, each of which is described using a custom attribute named VehicleDescriptionAttribute, as
follows:
// A custom attribute.
public sealed class VehicleDescriptionAttribute : System.Attribute
{
public string Description { get; set; }
}
public VehicleDescriptionAttribute(string vehicalDescription)
{
Description = vehicalDescription;
}
public VehicleDescriptionAttribute(){ }
As you can see, VehicleDescriptionAttribute maintains a piece of string data manipulated using an
automatic property (Description). Beyond the fact that this class derived from System.Attribute, there
is nothing unique to this class definition.
Note For security reasons, it is considered a .NET best practice to design all custom attributes as sealed. In
fact, Visual Studio provides a code snippet named Attribute that will dump out a new System.Attributederived class into your code window. See Chapter 2 for full explication of using code snippets; however, recall you
can expand any snippet by typing its name and pressing the Tab key twice.
Applying Custom Attributes
Given that VehicleDescriptionAttribute is derived from System.Attribute, you are now able to
annotate your vehicles as you see fit. For testing purposes, add the following class definitions to your
new class library:
// Assign description using a "named property."
[Serializable]
[VehicleDescription(Description = "My rocking Harley")]
pu &Ɩ26