17
\$\begingroup\$

I have the following method in .NET Core that returns the description attribute of an enum value. I think this code can be more elegant. I'd appreciate some suggestions.

public static string GetDescription(System.Enum input)
{
   Type type = input.GetType();
   MemberInfo[] memInfo = type.GetMember(input.ToString());

   if (memInfo != null && memInfo.Length > 0)
   {
      object[] attrs = (object[])memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
      if (attrs != null && attrs.Length > 0)
      {
         return ((DescriptionAttribute)attrs[0]).Description;
      }
    }

    return input.ToString();
}
\$\endgroup\$
1

1 Answer 1

33
\$\begingroup\$
   Type type = input.GetType();
   MemberInfo[] memInfo = type.GetMember(input.ToString());

You should use more meaningful variable names like enumType and enumMembers and your code could use some more LINQ and vars.


if (memInfo != null && memInfo.Length > 0)

This null check is unnecessary. The docs says about GetMember:

An array of MemberInfo objects representing the public members with the specified name, if found; otherwise, an empty array.

So we can remove one null check and test only the description-attribute and turn it into a ternary operator:

public static string GetDescription(System.Enum value)
{
    var enumMember = value.GetType().GetMember(value.ToString()).FirstOrDefault();
    var descriptionAttribute = 
        enumMember == null 
            ? default(DescriptionAttribute) 
            : enumMember.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
    return 
        descriptionAttribute == null 
            ? value.ToString() 
            : descriptionAttribute.Description;
}

I think this code can be more elegant

With C# 6 it can be just a small chain of method calls...

public static string GetDescription(Enum value)
{
    return
        value
            .GetType()
            .GetMember(value.ToString())
            .FirstOrDefault()
            ?.GetCustomAttribute<DescriptionAttribute>()
            ?.Description
        ?? value.ToString();        
}
\$\endgroup\$
2
  • 2
    \$\begingroup\$ I think your C# 6 example has different behaviour; it returns null if the description isn't present. How about adding ?? value.ToString() to the end? \$\endgroup\$
    – sclarke81
    Commented Apr 25, 2019 at 8:57
  • 1
    \$\begingroup\$ @sclarke81 yes, this totaly makes sense! \$\endgroup\$
    – t3chb0t
    Commented Apr 25, 2019 at 9:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.