Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert enums to human readable values

Does anyone know how to transform a enum value to a human readable value?

For example:

ThisIsValueA should be "This is Value A".

like image 278
Jedi Master Spooky Avatar asked Aug 17 '08 12:08

Jedi Master Spooky


2 Answers

Converting this from a vb code snippet that a certain Ian Horwill left at a blog post long ago... i've since used this in production successfully.

    /// <summary>     /// Add spaces to separate the capitalized words in the string,      /// i.e. insert a space before each uppercase letter that is      /// either preceded by a lowercase letter or followed by a      /// lowercase letter (but not for the first char in string).      /// This keeps groups of uppercase letters - e.g. acronyms - together.     /// </summary>     /// <param name="pascalCaseString">A string in PascalCase</param>     /// <returns></returns>     public static string Wordify(string pascalCaseString)     {                     Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");         return r.Replace(pascalCaseString, " ${x}");     } 

(requires, 'using System.Text.RegularExpressions;')

Thus:

Console.WriteLine(Wordify(ThisIsValueA.ToString())); 

Would return,

"This Is Value A". 

It's much simpler, and less redundant than providing Description attributes.

Attributes are useful here only if you need to provide a layer of indirection (which the question didn't ask for).

like image 183
Leon Bambrick Avatar answered Sep 17 '22 12:09

Leon Bambrick


The .ToString on Enums is relatively slow in C#, comparable with GetType().Name (it might even use that under the covers).

If your solution needs to be very quick or highly efficient you may be best of caching your conversions in a static dictionary, and looking them up from there.


A small adaptation of @Leon's code to take advantage of C#3. This does make sense as an extension of enums - you could limit this to the specific type if you didn't want to clutter up all of them.

public static string Wordify(this Enum input) {                 Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");     return r.Replace( input.ToString() , " ${x}"); }  //then your calling syntax is down to: MyEnum.ThisIsA.Wordify(); 
like image 30
Keith Avatar answered Sep 17 '22 12:09

Keith