kamagra how much to take

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:

  1. public enum Test
  2. {
  3. [Description("This Is X")]
  4. x = 1,
  5. [Description("This Is Y")]
  6. y = 2,
  7. }

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:

  1. public List<T> TestEnumRecursion(Test test)
  2. {
  3. FieldInfo fi = test.GetType().GetField(test.ToString());
  4. var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
  5. string x = (attributes.Length > 0) ? attributes[0].Description : test.ToString();
  6. return <method that builds up some typed collection of type T>.Where(obj => Equals(obj.<some property>, x)).ToList();
  7. }

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!

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>