Search code examples
.netenums

Convert Enum to String


Which is the preferred way to convert an Enum to a String?

  • Enum.GetName
  • Enum.Format
  • ToString
  • ??

Why should I prefer one of these over the others? Does one perform better?


Solution

  • As of C#6 the best way to get the name of an enum is the new nameof operator:

    nameof(MyEnum.EnumValue);
    
    // Ouputs
    > "EnumValue"
    

    This works at compile time, with the enum being replaced by the string in the compiled result, which in turn means this is the fastest way possible.

    Any use of enum names does interfere with code obfuscation, if you consider obfuscation of enum names to be worthwhile or important - that's probably a whole other question.