Using DescriptionAttribute And Reflection For Building Typed Collections Off Enumerations
Using DescriptionAttributes on enumerations is a very useful trick when you want to have another representation of the enumeration member in code. It is most helpful when you are passing strings and the such and at some point will need a reference back to the enum using that passed in string to match a member.
So assume you have the following enumeration:
- public enum Test
- [Description("This Is X")]
- x = 1,
- [Description("This Is Y")]
- y = 2,
No assume that you want to pass into an auxiliary method a Test type enumeration, which will in return pass back some strongly typed collection of objects. To do this, you need to use FieldInfo and DescriptionAttribute. Consider the following:
- public List<T> TestEnumRecursion(Test test)
- FieldInfo fi = test.GetType().GetField(test.ToString());
- var attributes = (DescriptionAttribute)fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
- string x = (attributes.Length > 0) ? attributes.Description : test.ToString();
- return <method that builds up some typed collection of type T>.Where(obj => Equals(obj.<some property>, x)).ToList();
Nothing real fancy going on here, FieldInfo discovers the attributes of a field and provides access to field metadata and DescriptionAttribute as demonstrated earlier specifies a description for a property or event. With some querying, we get a typed collection that we want with conditional property testing on that object!