Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if enum is obsolete

Tags:

c#

enums

How can I check if an enum if marked as obsolete?

public enum MyEnums
{
    MyEnum1,
    [Obsolete("How can you know that I'm obsolete?")]
    MyEnum2,
    MyEnum3
}

Now at runtime, I need to know which ones are obsolete:

foreach (var myEnum in Enum.GetValues(typeof(MyEnums)).Cast<MyEnums>())
{
    // How can I check if myEnum is obsolete?
}
like image 506
Drake Avatar asked Apr 23 '15 19:04

Drake


3 Answers

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
like image 162
M4N Avatar answered Nov 14 '22 07:11

M4N


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));
   }
like image 26
jbtule Avatar answered Nov 14 '22 07:11

jbtule


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));
like image 2
Matías Fidemraizer Avatar answered Nov 14 '22 08:11

Matías Fidemraizer