#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);
}

Advertisement

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: