14
\$\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\$
25
\$\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
    \$\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 Apr 25 at 8:57
  • 1
    \$\begingroup\$ @sclarke81 yes, this totaly makes sense! \$\endgroup\$ – t3chb0t Apr 25 at 9:24

protected by Jamal Jul 20 at 3:21

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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