Enum with spaces C#: If you give a space in string value of Enum, it would generate a compilation error. Single-word enum string value is a normal scenario and straightforward handle. But, how to have an enum string value with multiple words
Table of Contents
Enum values with spaces in C#
Normally, the name of an enum in c# can’t contain any special characters or spaces. There can be situations where we need to use friendly names for enums which have spaces in between.
For example, if you have a string value enum as below
public enum Country
{
India,
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 wherein you want string value enums with space between words. In that case, How to have enum values with spaces in C#?
You need to use Description attribute in this case. See the corrected enum snippet as below.
Associating Strings with enums in C#
In order to have a more friendly enum ,we can use System.ComponentModel.DescriptionAttribute. see the sample below,
public enum Country
{
India,
[Description("United Arab Emirates")]
UAE,
[Description("United Kingdom")]
UK
}
As above, by decorating with [Description] attribute you can have a valid enum for your case.
How to Get the Description Attribute Values from Enum?
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 by using reflection.
public static string GetDescriptionFromEnum(Enum value)
{
DescriptionAttribute attribute = value.GetType()
.GetField(value.ToString())
.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;
}
Summary
This article covered Enum with spaces C#. You need to use C# Enum Attribute, named Description to have an enum string value with multiple words. If you find this article useful share your feedback in the comments section.
Leave a Reply