Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 630
David Moorhouse Avatar asked Aug 09 '10 22:08

David Moorhouse


2 Answers

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 } 
like image 97
Scott Bartlett Avatar answered Sep 28 '22 00:09

Scott Bartlett


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.
like image 40
Stuart Helwig Avatar answered Sep 28 '22 01:09

Stuart Helwig