Check if enum is deprecated

How can I check if enum

, if it is marked as deprecated?

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 deprecated:

foreach (var myEnum in Enum.GetValues(typeof(MyEnums)).Cast<MyEnums>())
{
    // How can I check if myEnum is obsolete?
}

      

+3


source to share


4 answers


The following method checks if the enumeration value has an attribute Obsolete

:

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

      

+12


source


You can, but you will need to use reflection:

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

      

On the other hand, you can get all deprecated enum fields using LINQ:



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

      

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

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

      

+2


source


Thanks @ M4N here's a method to extend 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);
}

      

Name it like this:

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

      

0


source


Here's a very clean extension method. The trick is that you are reflecting a field with an enumeration type using the name of the enumeration.

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

      

0


source







All Articles