0

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?

Shewan
  • 61
  • 1
  • 10
  • PS I appreciate that I could make the extension method generic to apply to all enums, this is not what I am trying to do. – Shewan Nov 12 '22 at 10:57
  • this could be helpful https://stackoverflow.com/questions/29832536/check-if-enum-is-obsolete – Vivek Nuna Nov 12 '22 at 11:03

1 Answers1

1

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

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86