Created
February 4, 2019 19:44
-
-
Save cocowalla/f8002c14cbf5d35fd3e0b14e3db96c75 to your computer and use it in GitHub Desktop.
Enum display name extension method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Linq; | |
using System.Reflection; | |
namespace Acme.Utils | |
{ | |
public static class EnumExtensions | |
{ | |
// Note that we never need to expire these cache items, so we just use ConcurrentDictionary rather than MemoryCache | |
private static readonly ConcurrentDictionary<string, string> DisplayNameCache = new ConcurrentDictionary<string, string>(); | |
public static string DisplayName(this Enum value) | |
{ | |
var key = $"{value.GetType().FullName}.{value}"; | |
var displayName = DisplayNameCache.GetOrAdd(key, x => | |
{ | |
var name = (DescriptionAttribute[])value | |
.GetType() | |
.GetTypeInfo() | |
.GetField(value.ToString()) | |
.GetCustomAttributes(typeof(DescriptionAttribute), false); | |
return name.Length > 0 ? name[0].Description : value.ToString(); | |
}); | |
return displayName; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment