Skip to content

Instantly share code, notes, and snippets.

@cocowalla
Created February 4, 2019 19:44
Show Gist options
  • Save cocowalla/f8002c14cbf5d35fd3e0b14e3db96c75 to your computer and use it in GitHub Desktop.
Save cocowalla/f8002c14cbf5d35fd3e0b14e3db96c75 to your computer and use it in GitHub Desktop.
Enum display name extension method
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