Tuesday, 15 March 2016

Spaces in Enums

Hi,
 
Today when I was working with Enums and was blocked by a scenario where I need a Space in between the words of Enum. We all know that in Enums we cannot have a space. I was searching for solution and came to know that we can have a desciption as an annotation to the Enum item and read by reflections.
 
Here is the code for reading the description.
 
I have the below enum
 
public enum Date
{
   /// <remarks/>
   [Description("Created Date")]
   CreatedDate,
}
Below is the code which gets the description of Enum

public static string GetEnumDescription(Enum 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();
     }
}
 
Output

static void Main(string[] args)
{
    string strValueWithOutSpace = Date.CreatedDate.ToString();
    string strValueWithSpace = GetEnumDescription(Date.CreatedDate);
    Console.WriteLine("Without Space : " + strValueWithOutSpace);
    Console.WriteLine("With Space : " + strValueWithSpace);
    Console.Read();
}

 
Hope this helps.
 
--
Happy Coding

Gopinath

No comments:

Post a Comment