#470 – 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.

    /// <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”.

        [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");
        }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment