Search code examples
c#enumsreturn-valuereturn-type

C# numeric enum value as string


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? :)


Solution

  • 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
    }