C
C#2y ago
malkav

Get Enum Description with function

I had a helper function for this at some point, but I lost it.. How can I get the description tag from any enum? Say I have an enum:
public enum MyEnum
{
[Description("The first")]First,
[Description("The Second")]Second,
// ...
}
public enum MyEnum
{
[Description("The first")]First,
[Description("The Second")]Second,
// ...
}
and I wanted to get the description values returned, how would I go about it, regardless of Enum I put into the function? Preferably I would want to call MyEnum.GetDescription(MyEnum.First) or something to return "The First"
9 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega2y ago
public static string GetEnumDescription<T>(this T enumValue) where T : Enum
{
var enumFieldName = enumValue.ToString();
var field = typeof(T).GetField(enumFieldName);
if (field is null)
{
return "No description";
}

var attribute = field.GetCustomAttribute<DescriptionAttribute>();
return attribute is null ? "No description" : attribute.Description;
}
public static string GetEnumDescription<T>(this T enumValue) where T : Enum
{
var enumFieldName = enumValue.ToString();
var field = typeof(T).GetField(enumFieldName);
if (field is null)
{
return "No description";
}

var attribute = field.GetCustomAttribute<DescriptionAttribute>();
return attribute is null ? "No description" : attribute.Description;
}
Console.WriteLine(MyEnum.First.GetEnumDescription());
malkav
malkav2y ago
I get "FieldInfo does not contain a definition for 'GetCustomAttribute' and no accessible method 'GetCustomAttribute' accepting first argument of type 'FieldInfo' could be found"
Pobiega
Pobiega2y ago
Weird. I'm using .net 6
malkav
malkav2y ago
Whelp, oops. My IDE just lagged out and forgot to import references. My bad
Pobiega
Pobiega2y ago
new and improved version
public static string GetDescription<T>(this T enumValue, string defaultDescription = "No description") where T : Enum
{
var enumFieldName = enumValue.ToString();
var field = typeof(T).GetField(enumFieldName);
if (field is null)
{
return defaultDescription;
}

var attribute = field.GetCustomAttribute<DescriptionAttribute>();
return attribute is null ? defaultDescription : attribute.Description;
}
public static string GetDescription<T>(this T enumValue, string defaultDescription = "No description") where T : Enum
{
var enumFieldName = enumValue.ToString();
var field = typeof(T).GetField(enumFieldName);
if (field is null)
{
return defaultDescription;
}

var attribute = field.GetCustomAttribute<DescriptionAttribute>();
return attribute is null ? defaultDescription : attribute.Description;
}
it lets you specify the "no description" thing, in case its needed :p
malkav
malkav2y ago
Ah fair enough, thanks
Pobiega
Pobiega2y ago
also GetEnumDescription was too verbose, removed the "Enum" part (as the generic only works for enums anyways)
malkav
malkav2y ago
Fair enough, thanks a bunch!