Introduction
This tip presents a simple method to convert the items in an enumeration into string
s. 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
{
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