From 2b087feceb5f7a852e372ad3e704c01c086caae0 Mon Sep 17 00:00:00 2001 From: Neil Brommer Date: Thu, 13 Jul 2023 16:33:32 -0700 Subject: [PATCH] Add post on user friendly C# enums --- src/posts/UserFriendlyEnums.md | 70 ++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/posts/UserFriendlyEnums.md diff --git a/src/posts/UserFriendlyEnums.md b/src/posts/UserFriendlyEnums.md new file mode 100644 index 0000000..cacf246 --- /dev/null +++ b/src/posts/UserFriendlyEnums.md @@ -0,0 +1,70 @@ +--- +title: User Friendly C# Enums +description: A couple of extension methods to make getting user friendly information from attributes on enums +tags: [ Programming, C# ] +--- + +These extension methods will get the name and description from the `[Display]` attribute on enums. This allows you to add user-friendly names and descriptions on the enums themselves. + +## How to use + +```csharp +public enum MyEnum +{ + [Display(Name = "First Value", Description = "First value description")] + FirstValue, + [Display(Name = "Second Value")] + SecondValue, + ThirdValue +} + +MyEnum.FirstValue.GetDisplayName(); // "First Value" +MyEnum.ThirdValue.GetDisplayName(); // "ThirdValue" + +MyEnum.FirstValue.GetDisplayDescription(); // "First value description" +MyEnum.SecondValue.GetDisplayDescription(); // null +MyEnum.ThirdValue.GetDisplayDescription(); // null + +// Generate a list of options from an enum +IList options = Enum.GetValues() + .Select(e => e.GetDisplayName()) + .ToList(); +``` + +## Code + +```csharp +using System.ComponentModel.DataAnnotations; +using System.Reflection; + +public static class Extensions +{ + #region Enum DisplayAttribute + + /// + /// Gets the name from the DisplayAttribute or returns the enum as a string + /// if there is no DisplayAttribute name + /// + public static string GetDisplayName(this Enum value) + { + return value.GetType() + .GetMember(value.ToString()) + .First() + .GetCustomAttribute() + ?.Name + ?? value.ToString(); + } + + /// Gets the description from the DisplayAttribute + public static string? GetDisplayDescription(this Enum value) + { + return value.GetType() + .GetMember(value.ToString()) + .FirstOrDefault() + ?.GetCustomAttribute() + ?.Description; + } + + #endregion +} +```