Mar 26, 2010

Treating Enums as Strings in C#

Whenever I’m away from C# for a while I forget how to do some simple things. Googling on how to get the string equivalent of an enumeration in C#, turns up lots of hits but most of them take a very convoluted approach.

Here’s the easiest way I know  to treat an enum as a string. Given the RelayState enum:

public enum RelayState
    Invalid = 0,
    One = 1,
    Two = 2,

You can create an instance of the enum and get the string equivalent as follows:

RelayState relay_state_test = RelayState.Two;
string relay_state_name = Enum.GetName(typeof (RelayState), relay_state);

When you display relay_state_name it will show “Two”.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.