Defining Your Own Custom Attribute

You can use predefined attributes to attach metadata to type members.
You can also define a custom attribute by creating a new class inheriting from System.Attribute.  The class name must end in “Attribute”.  You typically define a constructor that takes arguments that consist of the metadata that you want to attach to the type member.
1
2
3
4
5
6
7
8
9
10
11
12
13
/// <summary>
/// Attach to a class method to indicate kg of methane that is
/// output when calling the method.
/// </summary>
public class MethaneFootprintAttribute : Attribute
{
    public double kgMethane;
 
    public MethaneFootprintAttribute(int kg)
    {
        kgMethane = kg;
    }
}
You can use the new attribute to attach metadata to individual type members.  You use the name of the new class, without the trailing “Attribute”.


1
2
3
4
5
6
7
8
9
10
11
[MethaneFootprint(45)]
public void FeedCowInBarn()
{
    Console.WriteLine("Cow eats slop in dim confines of barn");
}
 
[MethaneFootprint(29)]
public void LetGrazeOutside()
{
    Console.WriteLine("Cow enjoys grazing and ends up healthier");
}