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

        public void FeedCowInBarn()
            Console.WriteLine("Cow eats slop in dim confines of barn");

        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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: