Click here to Skip to main content
13,706,244 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

9.2K views
12 bookmarked
Posted 5 Jul 2017
Licenced CPOL

How to Display Friendly Names for Enumerations in C#?

, 5 Jul 2017
Rate this:
Please Sign up or sign in to vote.
Displaying friendly names for enumeration elements using the Description annotation

Introduction

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.

The Code

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 print the enumeration elements names, we will iterate over the names of the Enumeration type, append each name to a string builder and then display it on a message box, see the below code snippet:

var stringBuilder = new StringBuilder();

 foreach (string colorEnum in Enum.GetNames(typeof(ColorsEnum)))
 {
        stringBuilder.AppendLine(colorEnum);
 }

 MessageBox.Show(this, stringBuilder.ToString(), "Enumeration None Friendly Names");

The result of executing the above code will be displaying the color names, as they are defined in the enumeration type (in their non-friendly format).

Below is the message box that will be shown once we run the above code:

enumeration-nonfriendly-names

The above code resulted in printing out the names, as defined in the ColorsEnum enumeration data type.

As you can note, the 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, 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 ColorsEnum
    {
        [Description("-- Blanched Almond --")]
        BlanchedAlmond = 1,
        [Description("-- Dark Sea Green --")]
        DarkSeaGreen = 2,
        [Description("-- Deep Sky Blue --")]
        DeepSkyBlue = 3,
        [Description("-- Rosy Brown --")]
        RosyBrown = 4
    }

The Description attribute decoration is used to define a descriptive name for a given 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 (Please refer to my blog post Extension Methods in .NET to learn more about writing extension methods).

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 is an extension method that can be used by any enumeration data type:

public static string GetDescription(this Enum GenericEnum)
        {

            Type genericEnumType = GenericEnum.GetType();
            System.Reflection.MemberInfo[] memberInfo = 
                        genericEnumType.GetMember(GenericEnum.ToString());

            if ((memberInfo != null && memberInfo.Length > 0))
            {

                dynamic _Attribs = memberInfo[0].GetCustomAttributes
                      (typeof(System.ComponentModel.DescriptionAttribute), false);
                if ((_Attribs != null && _Attribs.Length > 0))
                {
                    return ((System.ComponentModel.DescriptionAttribute)_Attribs[0]).Description;
                }
            }

            return GenericEnum.ToString();
        }

Now that we wrote our extension method, we are ready to use this method with our ColorsEnum datatype.

Therefore, the below code will show the implementation of printing the friendly enumeration names:

StringBuilder stringBuilder = new StringBuilder();

            foreach (ColorsEnum colorEnum in Enum.GetValues(typeof(ColorsEnum)))
            {
                stringBuilder.AppendLine(colorEnum.GetDescription());
            }

            MessageBox.Show(this, stringBuilder.ToString(), "Enumeration Friendly Names");

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).

The execution result of the above code is illustrated within the below figure:

enumeration-friendly-names

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.

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. ??

Bonus

My spectacular reader! I am dedicating you a breathtakingly beautiful and relaxing classical music: Mozart – Piano Sonata No. 11 in A major, K. 331 – I. Andante grazioso

Happy coding and listening!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Aram Tchekrekjian
Technical Lead
Jordan Jordan
My name is Aram Tchekrekjian, I’m a passionate software developer with 7+ years of overall experience in various development languages including vb.net, c#, java and some php, during which I gained abundant of knowledge in Asp.net Web Forms, Asp.net Web Api, javascript, bootstrap, entity framework, WCF, windows forms, SQL server, MySQL as well as Android.

Currently I am an android developer and a scrum master within a cross-location teams working on multi-platform project, managing a Jenkins CI for multiple projects on an ubuntu server. My main interests are: git, docker, SEO, digital marketing.

I work as a Corporate Technical Lead in the Digital Solutions Team at Aramex International in Amman, Jordan.


You may also be interested in...

Comments and Discussions

 
GeneralRealy? Pin
SergeyAB7-Jul-17 7:43
memberSergeyAB7-Jul-17 7:43 
Question[My vote of 2] What's new? Pin
Bernhard Hiller7-Jul-17 3:38
professionalBernhard Hiller7-Jul-17 3:38 
QuestionNice article and an alternate source Pin
asiwel6-Jul-17 7:36
memberasiwel6-Jul-17 7:36 
QuestionAlternative approach Pin
si6185-Jul-17 20:20
membersi6185-Jul-17 20:20 
AnswerRe: Alternative approach Pin
tbayart6-Jul-17 2:28
membertbayart6-Jul-17 2:28 
AnswerAnother alternative approach. Pin
Paulo Zemek6-Jul-17 10:25
professionalPaulo Zemek6-Jul-17 10:25 
GeneralRe: Another alternative approach. Pin
si6186-Jul-17 14:26
membersi6186-Jul-17 14:26 
QuestionWhy dynamic? Pin
Paulo Zemek5-Jul-17 13:48
professionalPaulo Zemek5-Jul-17 13:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180920.1 | Last Updated 5 Jul 2017
Article Copyright 2017 by Aram Tchekrekjian
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid