Monday, April 14, 2014

enum description attributes in C#

given something like this...

using System.ComponentModel;
namespace DummyDevExpressApplication.Models
{
   public enum PlanetType
   {
      Inner,
      [Description("Gas Giant")]
      Gas,
      Dwarf
   }
}

 
 

...one may call the following (using the System.ComponentModel and using System.Reflection namespaces) to get "Gas Giant" into a string, in this case a string called "whatever"

string whatever;
PlanetType myType = PlanetType.Gas;
FieldInfo fieldInfo = myType.GetType().GetField(myType.ToString());
if (fieldInfo != null)
{
   object[] attrs = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
   if (attrs != null && attrs.Length > 0)
   {
      whatever = ((DescriptionAttribute)attrs[0]).Description;
   }
}

No comments:

Post a Comment