Tuesday, June 5, 2018

Get String of Enum

Several times I've had a situation come up where I wanted to get the string value of a custom Enum and I've gone different routes each time. Now, there's an easy, built-in, really fast way to get the name of an Enum, like this:
   1:  public enum PersonAttributes
   2:  {
   3:      FirstName,
   4:      LastName,
   5:      Age
   6:  }
If all I'm after is the name of the Enum then I can do this:
var name = Enum.GetName(typeof(PersonAttributes), PersonAttributes.FirstName);
The advantage of this approach is that it's fast. In my tests, this call completes in about 00:00:00.0001430, which is less than a millisecond. The drawback is that what I end up with is "FirstName", which isn't properly cased. If I wanted to use that Enum name in a form or a message or something, it isn't particularly helpful.

This time around what I really needed was a way to specify some rather arbitrary text instead of the name of the Enum. I stumbled across this Stack Overflow answer and I really like the way it works. As is the purpose of this blog, I'm writing about it for my future use. All we have to do is write an extension method, which the poster calls ToDescription. Then we add a Description attribute to each Enum and let it go. Here's the new Enum:
   1:  public enum PersonAttributes
   2:  {
   3:      [Description("First Name")]
   4:      FirstName,
   5:      [Description("Last Name")]
   6:      LastName,
   7:      Age
   8:  }

And then the extension method looks like this:
   1:  public static class AttributesHelperExtension
   2:  {
   3:      public static string ToDescription(this Enum value)
   4:      {
   5:          var da = (DescriptionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
   6:          return da.Length > 0 ? da[0].Description : value.ToString();
   7:      }
   8:  }

Now when we want to get the description we can just call it like this:
var description = PersonAttributes.FirstName.ToDescription();

The advantages and drawbacks of this approach are the inverse of the earlier method. This is slower, but gives us a useful value. Also, when I say slower, it takes 00:00:00.0132981, which is about 13 milliseconds. Totally acceptable to me.

No comments:

Post a Comment