Method that returns description attribute of enum value

Posted on

Problem

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();
}

Solution

   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();        
}

Leave a Reply

Your email address will not be published. Required fields are marked *