2

I'm trying to get a list of all Classes with a specific Attribute and Enum parameter of the Attribute.

View my example below. I realize how to get all Classes with Attribute GenericConfig, however how do I then filter down on parameter?

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // get me all classes with Attriubute GenericConfigAttribute and Parameter Type1
            var type1Types =
                    from type in Assembly.GetExecutingAssembly().GetTypes()
                    where type.IsDefined(typeof(GenericConfigAttribute), false)
                    select type;

            Console.WriteLine(type1Types);
        }
    }

    public enum GenericConfigType
    {
        Type1,
        Type2
    }

    // program should return this class
    [GenericConfig(GenericConfigType.Type1)]
    public class Type1Implementation
    {
    }

    // program should not return this class
    [GenericConfig(GenericConfigType.Type2)]
    public class Type2Implementation
    {
    }

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    public class GenericConfigAttribute : Attribute
    {
        public GenericConfigType MyEnum;

        public GenericConfigAttribute(GenericConfigType myEnum)
        {
            MyEnum = myEnum;
        }
    }
}
aherrick
  • 19,799
  • 33
  • 112
  • 188

1 Answers1

3

You can just add this to your query:

where type.GetCustomAttribute<GenericConfigAttribute>().MyEnum == GenericConfigType.Type1

For example:

var type1Types =
    from type in Assembly.GetExecutingAssembly().GetTypes()
    where type.IsDefined(typeof(GenericConfigAttribute), false)
    where type.GetCustomAttribute<GenericConfigAttribute>().MyEnum 
        == GenericConfigType.Type1
    select type;

Or simplified slightly (and safer):

var type1Types =
    from type in Assembly.GetExecutingAssembly().GetTypes()
    where type.GetCustomAttribute<GenericConfigAttribute>()?.MyEnum 
        == GenericConfigType.Type1
    select type;

And if you need to cope with multiple attributes on the same type, you can do this:

var type1Types =
    from type in Assembly.GetExecutingAssembly().GetTypes()
    where type.GetCustomAttributes<GenericConfigAttribute>()
        .Any(a => a.MyEnum == GenericConfigType.Type1)
    select type;
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • Just one more thing to consider: `GenericConfigAttribute` is `AllowMultiple = true` which means that it will throw a `AmbiguousMatchException` if there are more than one attribute on a class. – Yeldar Kurmangaliyev Nov 27 '18 at 16:55
  • @YeldarKurmangaliyev Fair point, added in something for that situation too. – DavidG Nov 27 '18 at 16:58