none
Getting the Description of the Enum Value. RRS feed

  • Question


  • Hi all,

     I have an Enum in my code which returns the friuts data, but with that i want to get some description for that like
     
    public enum FruitType {Apple, Grapes};
    Now i want some description to be fetch when i selected Apple.

    Can you help me...

    Thanks,
    Monday, May 21, 2012 12:52 PM

Answers

  • Hi,

     for this you can add a DescriptionAttribute for every enum type like the below


     public enum FruitType {DescriptionAttribute("This is Apple")Apple, DescriptionAttribute("This is Grapes")Grapes};

    Now if you want to fetch these description simply get its custom Attribute and fetch its description data as shown below.

    public string FriutTypeDescription(Enum FruitType)
            {
                FieldInfo fi = FruitType.GetType().GetField(FruitType.ToString());
                DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0)
                {
                    return attributes[0].Description;
                }
                else
                {
                    return FruitType.ToString();
                }
            }

    Hope it will help you..

    Sai Kumar K (MCP)
    Blog: Sai's Stuff.
    WebSite: SantoshTechnologies.
    MCP ID:Microsoft Transcript.

    • Marked as answer by Harshit_SK Monday, May 21, 2012 12:59 PM
    Monday, May 21, 2012 12:57 PM

All replies

  • Hi,

     for this you can add a DescriptionAttribute for every enum type like the below


     public enum FruitType {DescriptionAttribute("This is Apple")Apple, DescriptionAttribute("This is Grapes")Grapes};

    Now if you want to fetch these description simply get its custom Attribute and fetch its description data as shown below.

    public string FriutTypeDescription(Enum FruitType)
            {
                FieldInfo fi = FruitType.GetType().GetField(FruitType.ToString());
                DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0)
                {
                    return attributes[0].Description;
                }
                else
                {
                    return FruitType.ToString();
                }
            }

    Hope it will help you..

    Sai Kumar K (MCP)
    Blog: Sai's Stuff.
    WebSite: SantoshTechnologies.
    MCP ID:Microsoft Transcript.

    • Marked as answer by Harshit_SK Monday, May 21, 2012 12:59 PM
    Monday, May 21, 2012 12:57 PM
  • Hi Sai,

     I tried this and working great !!!!

    Thanks a lot for simple solution...

    Monday, May 21, 2012 12:59 PM