C# numeric enum value as string

David Moorhouse picture David Moorhouse · Aug 10, 2010 · Viewed 82.3k times · Source

I have the following enum:

public enum Urgency {
    VeryHigh = 1,
    High     = 2,
    Routine  = 4
}

I can fetch an enum "value" as string like this:

((int)Urgency.Routine).ToString() // returns "4"  

Note: This is different from:

Urgency.Routine.ToString() // returns "Routine"
(int)Urgency.Routine       // returns 4

Is there a way I can create an extension class, or a static utliity class, that would provide some syntactical sugar? :)

Answer

Scott Bartlett picture Scott Bartlett · Aug 10, 2010

You should just be able to use the overloads of Enums ToString method to give it a format string, this will print out the value of the enum as a string.

public static class Program
{
    static void Main(string[] args)
    {
        var val = Urgency.High;
        Console.WriteLine(val.ToString("D")); 
    }
}

public enum Urgency 
{ 
    VeryHigh = 1,
    High = 2,
    Low = 4
}