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
{
   ///
   [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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s