1: public enum PersonAttributes
2: {
3: FirstName,
4: LastName,
5: Age
6: }
var name = Enum.GetName(typeof(PersonAttributes), PersonAttributes.FirstName);
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