Search code examples
c#listenumsannotations

How do I make a list of non-obsolete Enum values


I have an enum which has obsolete values. I would like to return a list of the enum values which are not obsolete. I can return a list of all enum values but I can't identify the obsolete values to exclude them from the list.

Here is some sample code to illustrate the issue. First, here is a sample enum with the second value marked obsolete:

    public enum MyEnum
    {
        Item1 = 1,
        [Obsolete]
        Item2 = 2,
        Item3 = 3
    }

Here is a sample extension method that returns all values of the enum as a list:

    public static class MyEnumExt
    {
        /// <summary>
        /// I want to amend this method to return a list only including the 
        /// enum values that are not obsolete
        /// </summary>
        public static List<MyEnum> GetList(this MyEnum t)
        {
            return Enum.GetValues(t.GetType()).Cast<MyEnum>().ToList();
        }
    }

Does anyone have any suggestions for amending my extension method to return only values that are not marked obsolete?


Solution

  • You can change it like this:

    public static List<MyEnum> GetList()
    {
        Type type = typeof(MyEnum);
        return Enum.GetValues(type)
            .Cast<MyEnum>()
            .Where(t => type.GetField(t.ToString()).GetCustomAttribute<ObsoleteAttribute>() == null)
            .ToList();
        
    }
    

    Basically you need to get the field that corresponds to the enum value, and then check that it isn't decorated with ObsoleteAttribute.

    Note that GetCustomAttribute<T> is an extension method, so you'll need using System.Reflection;.

    Try it online