Click here to Skip to main content
15,907,906 members
Articles / Programming Languages / C#
Tip/Trick

How to Generate Element Names for an Enumeration

Rate me:
Please Sign up or sign in to vote.
4.52/5 (14 votes)
2 Oct 2017CPOL2 min read 16.8K   10   12
I present a simple method to convert the elements in an enumeration into strings. This tip is suitable for enumerations whose elements are of the form RedAndBlack, which readily converts to "Red And Black".

Introduction

This tip presents a simple method to convert the items in an enumeration into strings. It is assumed that the items in the enumeration have sensible human readable names such as ConvertToPoundsSterling which would become "Convert To Pounds Sterling". This is in any case good programming practice.

The advantage of the mechanism presented here is that it works with existing enumerations such as System.Drawing.Color. As an example, System.Drawing.Color.LightBlue would convert to "Light Blue".

There are alternative ways to achieve the same result, one being to add attributes to the enumeration definition. That has the advantage that the text can take any form, but it does not work with existing enumerations.

Requirements

You will need a basic understanding of C#.

Note that you do not need to understand the code in order to use it. Just skip to the "Using the Code" section.

Converting Enumeration Elements to Strings

An enumeration can be converted into text as follows:

C#
MyEnumeration item = MyEnumeration.DateOfBirth;
var r = new System.Text.RegularExpressions.Regex(@"(?<=[^A-Z])(?=[A-Z]) | 
(?=[A-Z][^A-Z])", System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);
string description = r.Replace(item.ToString(), " ").Trim();

The code uses the Regex framework to perform the insertion of spaces into the enumeration string. It assumes that MyEnumeration.DateOfBirth should transform to "Date Of Birth" whereas ExampleEnumeration.RawMRZData should become "Raw MRZ Data" and not "Raw M R Z Data".

You can of course modify the conversion to suit your own needs. For example, you might wish to replace " To " with " to ".

When performing many conversions, it makes sense to store the enumerations and their string representations in a dictionary, thereby reducing the execution time overhead.

The EnumItemMap class encapsulates enumeration conversion and an enumeration string dictionary:

C#
public class EnumItemMap
{
    /*
     * Given an enum, construct a map where the keys are the enum items
     * and the values are string descriptions of each item. Example:
     *
     * {TheFirst, "The First"},
     * {TheSecond, "The Second"},
     * {AndTheLast, "And The Last"},
     *
     * Thus each enum item is converted to text and split at each capital letter.
     */
    public static Dictionary<T, string> Build<T>() where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException
              ("Error: EnumItemMap.Build<T>() => T must be an enumerated type");
        }

        Dictionary<T, string> map = new Dictionary<T, string>();
        var values = Enum.GetValues(typeof(T));
        foreach (var item in values)
        {
            var r = new System.Text.RegularExpressions.Regex(
                @"(?<=[^A-Z])(?=[A-Z]) | (?=[A-Z][^A-Z])",
                System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);

            map[(T)item] = r.Replace(item.ToString(), " ").Trim();
        }
        return map;
    }
}

The code first creates a dictionary instance and a list of the items in the enumeration. It then loops over each item in the list. It converts each item to a text string, such as "ThisIsAnItem", and then inserts spaces into the string, giving "This Is An Item" in the case of the example. Lastly, it inserts the item and the corresponding string into the dictionary/map.

Note that I have tried to prevent the method from being invoked for non enumeration types, using the 'where' keyword, and a runtime check on T which throws an exception if T is not an enumeration type. Unfortunately, there appears to be no compile time mechanism to ensure that the parameterised type T is an enumeration.

Using the Code

The EnumItemMap.Build method is very easy to use.

Consider the following example enumeration:

C#
public enum DataType
{
    RawMRZData = 0,
    LineOne = 1,
    LineTwo = 2,
    LineThree =  3,
    Type = 4,
    DocumentNumber =  5,
    FirstName = 6,
    LastName = 7,
    DateOfBirth = 8,
    DateOfExpiry = 9,
    IssuingState = 10,
    Nationality = 11,
    Gender = 12,
    OptionalDataOne = 13,
    OptionalDataTwo = 14,
    FailureStatus = 15,
}

First, we create a map of item string pairs for the above enumeration:

C#
Dictionary<DataType, string> mapDataType = EnumItemMap.Build<DataType>();

We can now convert the DataType.FirstName item to a string as follows:

C#
string description = mapDataType[DataType.FirstName];

The description variable will contain "First Name".

History

  • 25th September 2017: First version
  • 26th September 2017: Various improvements to the text
  • 2rd October 2017: Added a Trim() to remove leading and trailing whitespaces, as suggested by Stephen Fletcher

License

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


Written By
United Kingdom United Kingdom
C#/WPF/C++ Windows developer

Comments and Discussions

 
PraisePerfect timing Pin
no_in3-Oct-17 6:46
professionalno_in3-Oct-17 6:46 
QuestionSaves Not Having to Use the Description Attribute Pin
Hyland Computer Systems28-Sep-17 11:20
Hyland Computer Systems28-Sep-17 11:20 
BugLeading Space Pin
Stephen Fletcher27-Sep-17 9:00
Stephen Fletcher27-Sep-17 9:00 
GeneralRe: Leading Space Pin
Leif Simon Goodwin2-Oct-17 21:53
Leif Simon Goodwin2-Oct-17 21:53 
QuestionA suggestion, well two Pin
Wendelius25-Sep-17 5:16
mentorWendelius25-Sep-17 5:16 
AnswerRe: A suggestion, well two Pin
Leif Simon Goodwin25-Sep-17 5:25
Leif Simon Goodwin25-Sep-17 5:25 
GeneralRe: A suggestion, well two Pin
Wendelius25-Sep-17 5:36
mentorWendelius25-Sep-17 5:36 
GeneralRe: A suggestion, well two Pin
Leif Simon Goodwin25-Sep-17 10:27
Leif Simon Goodwin25-Sep-17 10:27 
AnswerRe: A suggestion, well two Pin
Simon Ferry26-Sep-17 2:51
Simon Ferry26-Sep-17 2:51 
Interesting suggestion, what can I say
PraiseRe: A suggestion, well two Pin
asiwel4-Oct-17 9:23
professionalasiwel4-Oct-17 9:23 
QuestionIsn't this the sort of thing you would solve with DescriptionAttribute Pin
Sacha Barber25-Sep-17 4:13
Sacha Barber25-Sep-17 4:13 
AnswerRe: Isn't this the sort of thing you would solve with DescriptionAttribute Pin
Leif Simon Goodwin25-Sep-17 4:51
Leif Simon Goodwin25-Sep-17 4:51 

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.