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? :)
If you wanted, you could make the extension method work for all enums:
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.
Great stuff ... I have now added an extension method to my project
Now I can get the int value - as a string - by calling
Urgency.Routine.NumberString();
Thanks to Frankentosh and Jon :)How about a little reflection? Should work with all underlying types.
Then:
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:
Then, used an extension method like this:
You can then just call
in order to display your enum as more readable text.If you want to just deal with this enum, use Mark Byer's solution.
For a more general solution:
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.