Wednesday, November 22, 2006

HOWTO: Read attributes from an enumeration member

Today I needed to read custom attributes from members of an enumeration type. As the found solution did not strike me as immediately obvious, I'm posting here for future reference:

Thing foo = Thing.Bar;
FieldInfo field
= foo.GetType().GetField(foo.ToString());
object[] attrs = field.GetCustomAttributes(typeof(Description), false);

where Thing is an enumeration, defined something like:

public enum Thing {
"Foo thing")]
"Baz thing")]

Technorati tags: ,

No comments: