Home > Net >  Microsoft.OpenApi.Extensions Enum.GetDisplayName() doesn't work, works fine when copied over
Microsoft.OpenApi.Extensions Enum.GetDisplayName() doesn't work, works fine when copied over

Time:11-26

Wanting a quick way to set a display for Enums without creating an enum class, I came across [Display(Name = "display name")] I was going to write my own method but found Microsoft.OpenApi.Extensions.EnumExtensions.GetDisplayName.

public static string GetDisplayName(this Enum enumValue)
{
    var attribute = enumValue.GetAttributeOfType<DisplayAttribute>();
    return attribute == null ? enumValue.ToString() : attribute.Name;
}

It doesn't work, returning the enum.ToString() value, but if I copy over the method as is into my project, it works fine. Any idea why? Running .net 5.0 enter image description here

CodePudding user response:

They check for their own Microsoft.OpenApi.Attributes.DisplayAttribute.

Either roll your own extension method, pointing to Systems.ComponentModel.DataAnnotations.DisplayAttribute, or (less preferably) apply their DisplayAttribute to your enum.

  • Related