Get description of optionSet

Enumeration :

public enum Country
{

[Display(Description=”Tunisia”)]
Tunisia = 1,

[Display(Description=”France”)]
France = 2,

[Display(Description=”UnitedState”)]
UnitedState = 3,
}

To get the description of enumeration :


public static string GetDescriptionFromEnumValue(Enum value)
{
if (value == null)
return null;
try
{
var fieldInfo = value.GetType().GetField(value.ToString());
if(fieldInfo == null)
{ return null;
}
DisplayAttribute attribute = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false).SingleOrDefault() as DisplayAttribute;
return attribute.Description;
}
//if the value of enum doesn't exist
catch (Exception ex)
{
throw;
}
}

Advertisements