#471 – Reading the Value of an Attribute Using Reflection

The purpose of creating a custom attribute is so that some tool or application code can read the data at runtime and make use of it.  You can use reflection to read custom attribute data at runtime.

You use the static Attribute.GetCustomAttribute method to retrieve an object representing your custom attribute, from a specific type member.

In the example below, I iterate through all of the methods of the Cow class and then call GetCustomAttribute to see which ones have an attached MethaneFootprintAttribute.

foreach (MethodInfo mi in typeof(Cow).GetMethods())
    Console.WriteLine("Method Cow.{0}", mi.Name);

    MethaneFootprintAttribute methAtt =
        (MethaneFootprintAttribute) Attribute.GetCustomAttribute(mi, typeof(MethaneFootprintAttribute));

    if (methAtt != null)
        Console.WriteLine("  - Methane: {0}", methAtt.kgMethane);