Thursday, June 19, 2014

C# - Enum Fully Qualified Name with space and Display

In Enum we can not have fully qualified name with spaces. To achieve that we can add the description attribute as follows

     ....
    using System.ComponentModel;
   ....

    public enum Employee
    {
        [Description("Balajiprasad Ramesh")]
        BalajiprasadRamesh = 1,
      
        [Description("Combined Name")]
        CombinedName = 2

    }



To display Enum description we can use the following code

private static string GetEnumDescription(object value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                typeof(DescriptionAttribute),
                false);

            if (attributes != null &&
                attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }

No comments:

Post a Comment