A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer


String value enum with space in between - Description Attribute

String value enum with space seperated words in C# need special attention.You need to use Description attribute.See the article for defining the enum and fetching the value.

Single word enum string value is a normal scenario and straight forward handle.But,how to have an enum string value with multiple words.For example if you have a string value enum as below 

public enum Country
        United Arab Emirates,
        United Kingdom

 You will get syntax error since this is not the correct way of enum declaration.If you remove spaces in between string value, it will become a valid enum.


But there may be cases still where in you want string value enums with space between words.You need to use Description atrribute in this case.See the corrected enum snippet as below. 

public enum Country
    [Description("United Arab Emirates")]
    [Description("United Kingdom")]

 Above you seen to make a valid enum for your case.


Now, how to fetch the Description attribute values instead of enum values .Means, you need United Arab Emirates instead of UAE.You can use any of the method below for getting the Description attribute value from the corresponding enum value



public static string GetDescriptionFromEnum(Enum value)
            DescriptionAttribute attribute = value.GetType()
                .GetCustomAttributes(typeof(DescriptionAttribute), false)
                .SingleOrDefault() as DescriptionAttribute;
            return attribute == null ? value.ToString() : attribute.Description;


       public static string GetDescriptionFromEnum(Enum value)
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes == null && attributes.Length == 0 ? value.ToString() : attributes[0].Description;         

Add comment

  Country flag

  • Comment
  • Preview