To add to Bill's answer, there are a couple of problems with your original code.
var type = value.GetType();
var attributes = type.GetTypeInfo().GetCustomAttributes(...);
You're looking for attributes on the enum type itself, rather than attributes on the enum member. So:
[Enum("...")] private enum TestEnum { ... }
would match, but:
private enum TestEnum { [Enum("...")] Unknown }
wouldn't.
You need to find the field which corresponds to the enum value you're working with, and look for the attributes on that field.
.GetCustomAttributes(typeof(Enum), true);
The type you pass as the first parameter here needs to be the attribute type you're looking for. But instead of passing
typeof(EnumAttribute)
, you're passing
typeof(Enum)
. That is the
System.Enum
class, which is not an attribute, and won't match your custom attribute.
return ((EnumAttribute)attributes[0]).Name;
GetCustomAttributes
will return an empty array if there are no matching attributes. If that happens, your code will throw an
IndexOutOfRangeException
. You should test whether the attribute was found, and return a suitable alternative if it wasn't.
You can fix your code quite easily:
public static string ToDisplayName(this Enum value)
{
var enumType = value.GetType().GetTypeInfo();
var valueField = enumType.GetDeclaredField(value.ToString());
var attributes = valueField.GetCustomAttributes<EnumAttribute>(false);
if (attributes.Length == 0) return value.ToString();
return attributes[0].Name;
}