Skip to main content
Question Protected by Jamal
deleted 2 characters in body; edited tags
Source Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

I have the following method in .NET Core.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();
}

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

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();
}
Source Link
Sam
  • 335
  • 1
  • 2
  • 6

Method that returns description attribute of enum value

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