Check if enum is obsolete

The following method checks whether an enum value has the Obsolete attribute:

public static bool IsObsolete(Enum value)
{
    var fi = value.GetType().GetField(value.ToString());
    var attributes = (ObsoleteAttribute[])
        fi.GetCustomAttributes(typeof(ObsoleteAttribute), false);
    return (attributes != null && attributes.Length > 0);
}

You can use it like this:

var isObsolete2 = IsObsolete(MyEnums.MyEnum2); // returns true
var isObsolete3 = IsObsolete(MyEnums.MyEnum3); // returns false

You can, but you'll need to use reflection:

bool hasIt = typeof (MyEnums).GetField("MyEnum2")
                .GetCustomAttribute(typeof (ObsoleteAttribute)) != null;

In the other hand, you can get all obsolete enum fields using some LINQ:

IEnumerable<FieldInfo> obsoleteEnumValueFields = typeof (MyEnums)
              .GetFields(BindingFlags.Public | BindingFlags.Static)
              .Where(fieldInfo => fieldInfo.GetCustomAttribute(typeof (ObsoleteAttribute)) != null);

And finally, using above result, you can get all obsolete enum values!

IEnumerable<MyEnums> obsoleteEnumValues = obsoleteEnumValueFields
                                .Select(fieldInfo => (MyEnums)fieldInfo.GetValue(null));

Thanks @M4N here's an extension method approach of your solution:

public static bool IsObsolete(this Enum value)
{
    FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
    ObsoleteAttribute[] attributes = (ObsoleteAttribute[])fieldInfo.GetCustomAttributes(typeof(ObsoleteAttribute), false);
    return (attributes != null && attributes.Length > 0);
}

Call it like this:

bool isObsolete2 = MyEnums.MyEnum2.IsObsolete(); // true
bool isObsolete3 = MyEnums.MyEnum3.IsObsolete(); // false

Here is a very clean extension method. The trick is that you are reflecting on a field off of the enum's type using the enum's name.

   public static bool IsObsolete(this Enum value)
   {  
      var enumType = value.GetType();
      var enumName = enumType.GetEnumName(value);
      var fieldInfo = enumType.GetField(enumName);
      return Attribute.IsDefined(fieldInfo, typeof(ObsoleteAttribute));
   }

Tags:

C#

Enums