Quantcast
Channel: Dynamics 365 Customer Engagement
Viewing all articles
Browse latest Browse all 286

Spaces in Enums

$
0
0
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
 
publicenumDate
{
   ///<remarks/>
   [Description("Created Date")]
   CreatedDate,
}
Below is the code which gets the description of Enum

publicstaticstring 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

staticvoid 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

Viewing all articles
Browse latest Browse all 286

Trending Articles