Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Generate Element Names for an Enumeration

0.00/5 (No votes)
2 Oct 2017 1  
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:

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:

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:

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:

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

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

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here