C# - How to Display Friendly Names for Enumerations

AramT
2,109 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Definition

An Enumeration (or enum) is a data type that includes a set of named values called elements or members. The enumerator names are usually identifiers that behave as constants in the language.

Sometimes you might need to loop on the elements of a particular enum and print its element names, however as you know by the language constraints, the enum element names must follow the naming convention, you cannot include spaces or other special characters. Therefore printing the elements will lead to printing the defined non-friendly elements names.

In this article, I will be explaining and showing to you by a code sample how you can define and display friendly names for enumeration elements using the Description annotation.

Also I will be explaining a great way to blend the extension methods feature to write an easy-to-use extension method to get a generic enum’s description property’s value and return it to the caller process. If you need to learn about extension methods with interactive examples, check my tech.io lesson: understanding extension methods in .net

So to start, let’s say we have the below ColorsEnum enumeration type defined in C#:

public enum ColorsEnum
{
      BlanchedAlmond = 1,
      DarkSeaGreen = 2,
      DeepSkyBlue = 3,
      RosyBrown = 4
}

To get the enumeration elements names, we will iterate over the names of the Enumeration type, append each name to a string builder and then return the built string, see the below code snippet:

Showing how you can iterate over names dynamically using reflection
1
10
11
12
13
14
15
16
17
18
19
·// {...}
public static string GetColorEnums()
{
var stringBuilder = new StringBuilder();
foreach (string colorEnum in Enum.GetNames(typeof(ColorsEnum)))
{
stringBuilder.Append(colorEnum + "|");
}
return stringBuilder.ToString();
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

As you might have noticed from the above code, it resulted in displaying the names, as defined in the ColorsEnum enumeration data type. (With the same casing)

So in this case names are non-friendly names; that’s it, no spaces between names.

Sometimes we need to print out a given enumeration element name in a user-friendly format, maybe for logging purposes to be verbose when displaying the enum values or sometimes you might want to populate the enum elements into a dropb, in this case we will need to add an attribute decoration on each of the enumeration names. This attribute comes from the namespace System.ComponentModel.

The below code shows the updated version of the ColorsEnum, having the new Description attribute decoration applied to the enum names:

public enum FriendlyColorsEnum
    {
        [Description("Blanched Almond Color")]
        BlanchedAlmond = 1,
        [Description("Dark Sea Green Color")]
        DarkSeaGreen = 2,
        [Description("Deep Sky Blue Color")]
        DeepSkyBlue = 3,
        [Description("Rosy Brown Color")]
        RosyBrown = 4
    }

The Description attribute decoration is used to define a descriptive name for a give property or event. It can be used with either enum elements or with any user defined data type property or event.

The description decoration is defined under the System.ComponentModel Namespace, which should be imported directly in the code, or included within the project’s default references.

Even though we defined friendly descriptions for each of our enumeration elements, using the normal ToString() method will keep printing non-friendly names.

So, printing the descriptive friendly names that we defined requires an extension method.

This extension method will use reflection to get an array of the enum’s members, and then from the array’s first element’s member info it will check and return if the member has a Description attribute defined, if that attribute exists, then it will return the Description value, this will be contained within the GenericEnum variable’s ToString() method.

The code below includes the above-mentioned extension method, another function that calls this extension method while looping through the enum elements and then it returns a string with the friendly names (description attributes) of enum appended. Please note that the extension method that can be used by any enumeration data type, not particularly our example of ColorsEnum:

Showing how you can iterate over enum names dynamically using reflection
1
10
11
12
13
14
15
16
17
18
19
·// {...}
public static string GetFriendlyColorEnums()
{
StringBuilder stringBuilder = new StringBuilder();
foreach (FriendlyColorsEnum colorEnum in Enum.GetValues(typeof(FriendlyColorsEnum)))
{
stringBuilder.Append(colorEnum.GetDescription() + "|");
}
return stringBuilder.ToString();
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

As you have noticed, we are using the GetDescription method as it is part of the ColorsEnum(This is the power of the extension methods).

As you can see, we are now able to display the enumeration values in a user-friendly way instead of displaying them as their code names.

Exercise

The below exercise requires basic knowledge of generics, if you are new to this topic or you forgot the syntax of writing generic methods, then why not learn about generics in c# with in-depth article including interactive sample codes and exercises.

Convert the below enum extension method to generic
1
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
·// {...}
public static string GetDescription(this Enum GenericEnum) //Hint: Change the method signature and input paramter to use the type parameter T
{
Type genericEnumType = GenericEnum.GetType();
MemberInfo[] memberInfo = genericEnumType.GetMember(GenericEnum.ToString());
if ((memberInfo != null && memberInfo.Length > 0))
{
var _Attribs = memberInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if ((_Attribs != null && _Attribs.Count() > 0))
{
return ((System.ComponentModel.DescriptionAttribute)_Attribs.ElementAt(0)).Description;
}
}
return GenericEnum.ToString();
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Conclusion

An enumeration is a great way to define a set of constant values in a single data type. If you want to display an enum’s element name on your UI directly by calling its ToString() method, it will be displayed as it has been defined. This will give non-friendly look on the UI if the enum’s element name is a compound name. The description attribute decoration enables adding descriptive information on the enum’s element name, and then an extension method should be defined to read this decoration.

In this article, we defined description attribute decorations on an enum and implemented an extension method for enum to read these decorations and get the values from it.

I hope that I was able to simplify and explain how to display friendly names of enumerations in C#. Please let me know if you like this article. Try to implement this tutorial and if you need any help just leave me a comment

Article has been ported from CodingSonata.com

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content