C# numeric enum value as string

C#EnumsReturn ValueReturn Type

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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
}

Solution 2 - C#

In order to achieve more "human readable" descriptions for enums (e.g. "Very High" rather than "VeryHigh" in your example) I have decorated enum values with attribute as follows:

public enum MeasurementType
{
    Each,

    [DisplayText("Lineal Metres")]
    LinealMetre,

    [DisplayText("Square Metres")]
    SquareMetre,

    [DisplayText("Cubic Metres")]
    CubicMetre,

    [DisplayText("Per 1000")]
    Per1000,

    Other
}


public class DisplayText : Attribute
{

    public DisplayText(string Text)
    {
        this.text = Text;
    }


    private string text;


    public string Text
    {
        get { return text; }
        set { text = value; }
    }
}

Then, used an extension method like this:

    public static string ToDescription(this Enum en)
    {

        Type type = en.GetType();

        MemberInfo[] memInfo = type.GetMember(en.ToString());

        if (memInfo != null && memInfo.Length > 0)
        {

            object[] attrs = memInfo[0].GetCustomAttributes(
                                          typeof(DisplayText),

                                          false);

            if (attrs != null && attrs.Length > 0)

                return ((DisplayText)attrs[0]).Text;

        }

        return en.ToString();

    }

You can then just call

myEnum.ToDescription()
in order to display your enum as more readable text.

Solution 3 - C#

If you want to just deal with this enum, use Mark Byer's solution.

For a more general solution:

public static string NumberString(this Enum enVal) 
{
    return Convert.ToDecimal(enVal).ToString("0");
}

Converting to decimal means you don't need to deal with the 8 different allowed underlying integral types explicitly, as all of them convert losslessly to decimal but not to each other (ulong and long don't convert losslessly between each other but both can handle all the rest). Doing that would probably be faster (esp. if you pick well in your order of comparison), but a lot more verbose for relatively little gain.

Edit:

The above isn't as good as Frankentosh's though, Frankentosh saw through the question to the real problem and solves it very eloquently.

Solution 4 - C#

Great stuff ... I have now added an extension method to my project

public static class EnumExtensions 
{ 
    public static string NumberString(this Enum enVal) 
    { 
        return enVal.ToString("D"); 
    }
} 

Now I can get the int value - as a string - by calling Urgency.Routine.NumberString(); Thanks to Frankentosh and Jon :)

Solution 5 - C#

You can write an extension method for your specific type:

public static class UrgencyExtension
{
    public static string ToIntegerString(this Urgency u)
    {
        return ((int)u).ToString();
    }
}

Use as follows:

Urgency u = Urgency.Routine;
string s = u.ToIntegerString();

Solution 6 - C#

How about a little reflection? Should work with all underlying types.

public static class EnumTools
{
	public static string ToRawValueString(this Enum e)
	{
		return e
			.GetType()
			.GetFields(BindingFlags.Public | BindingFlags.Static)
			.First(f => f.Name==e.ToString())
			.GetRawConstantValue()
			.ToString();
	}
}

Then:

Console.WriteLine(Urgency.High.ToRawValueString()); //Writes "2"

Solution 7 - C#

a simple approach

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

Solution 8 - C#

If you wanted, you could make the extension method work for all enums:

public static string ToValueString(this Enum enumValue) 
{
    if (enumValue.GetType().GetEnumUnderlyingType() == typeof(int))
        return ((int)(object)enumValue).ToString();
    else if (enumValue.GetType().GetEnumUnderlyingType() == typeof(byte))
        return ((byte)(object)enumValue).ToString();
    ... 
}        

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid MoorhouseView Question on Stackoverflow
Solution 1 - C#Scott BartlettView Answer on Stackoverflow
Solution 2 - C#Stuart HelwigView Answer on Stackoverflow
Solution 3 - C#Jon HannaView Answer on Stackoverflow
Solution 4 - C#David MoorhouseView Answer on Stackoverflow
Solution 5 - C#Mark ByersView Answer on Stackoverflow
Solution 6 - C#spenderView Answer on Stackoverflow
Solution 7 - C#Lauda WangView Answer on Stackoverflow
Solution 8 - C#Kirk WollView Answer on Stackoverflow