Skip to content

[Feature] Enum must have DisplayName to get DisplayName #214

Open
@jzabroski

Description

@jzabroski
public class AB { }
public enum ABEnum { A = 0, B = 1}
public class Test
{
  public void TestAB()
  {
    foreach (var item in Enum.GetValues(typeof(AB))) // Feature logged in https://github.com/DotNetAnalyzers/ReflectionAnalyzers/issues/212
    {
      Console.WriteLine(((Enum)item).GetDisplayName()); // This issue: verify the enum has a [DisplayName] attribute on each value of the enum
                     // ^^^^^^^^^^^^ bonus: don't raise Possible InvalidCastException if typeof(AB) is an enum.
    }
  }
}

where GetDisplayName is defined as an extension method:

    public static string GetDisplayName(this Enum enumValue)
    {
      return enumValue.GetAttribute<DisplayAttribute>()?.Name;
    }

Is this do-able? In the general case if GetDisplayName is in a different library, how will you know to peer into the extension method to validate its behavior? On one hand, the only scenarios I know of for putting extension methods on enums are exactly this scenario. On the other, I don't want to complicate ReflectionAnalyzers with potentially slow analyzers. Would this be efficient?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions