Converting an Enum to its string representation

I inherited a particularly nasty piece of legacy code and in the process of wrapping it into a cleaner interface I decided to use an enum as a parameter rather than a string. The reason was that strings are bad anyway but this particular bit of code was case sensitive as well.

If you have used an enum before you will know that it can represent numbers (usually int but also byte, sbyte, short, ushort, int, uint, long, and ulong) but not strings.

I created my enum and I was in the process of coding up a lookup table to convert my enum parameter back into a string when I found this handy method called Enum.GetName().

Using this method I can turn the enum constant into a string representation of itself.

Taking the enum:

using System;

// declares the enum
public enum OvenTemperature
{
    Low,
    Medium,
    High
}

I can then use this code to turn OvenTemperature.Low into the string “Low”:

// declare an instance of the enum
OvenTemperature ovenTemp = OvenTemperature.Low;

// convert its value to a string
string convertedOutput = Enum.GetName(typeof(OvenTemperature), ovenTemp);

// convertedOutput now equals "Low"

This solution only works if you need your string representation of the enum to be the exact same word that you use as the enum constant but when this situation arises it saves you having to maintain a separate lookup table for the conversion.

Complete sample console application

using System;

namespace ConvertEnumToStringRepresentation
{
    // declares the enum
    public enum OvenTemperature
    {
        Low,
        Medium,
        High
    }

    class ConvertEnumToStringRepresentationProgram
    {
        static void Main(string[] args)
        {
            // declare an instance of the enum
            OvenTemperature ovenTemp = OvenTemperature.Low;

            // convert its value to a string
            string convertedOutput = Enum.GetName(typeof(OvenTemperature), ovenTemp);

            // convertedOutput now equals "Low"
            Console.WriteLine("convertedOutput = " + convertedOutput);

            // pause execution so the example can be seen
            Console.ReadLine();
        }
    }
}

No comments :