26

Is there an elegant way to get all the types in an assembly that have a custom attribute?

So if I have a class

[Findable]
public class MyFindableClass
{}

I would like to be able to find it in a collection of types returned by Assembly.GetTypes(...)

I can do it with a big vile hack, but I'm sure someone has a nicer way.

Aidan
  • 4,783
  • 5
  • 34
  • 58
  • 3
    I'm not sure what you're considering a "big vile hack", but if it is a simple for loop, it isn't a hack; it's a good solution. – R. Martinho Fernandes Jan 31 '11 at 15:58
  • possible duplicate of [C# - how enumerate all classes with custom class attribute?](http://stackoverflow.com/questions/607178/c-sharp-how-enumerate-all-classes-with-custom-class-attribute) – nawfal Jun 09 '13 at 07:45
  • Important corollary question How do I read an attribute on a class at runtime? http://stackoverflow.com/questions/2656189/how-do-i-read-an-attribute-on-a-class-at-runtime – Chris Marisic Nov 02 '15 at 17:20

1 Answers1

48

I wouldn't think you can dodge enumerating every type in the assembly, checking for the attribute, but you could use LINQ to make the query easier to understand:

Assembly assembly = ...
var types = from type in assembly.GetTypes()
            where Attribute.IsDefined(type, typeof(FindableAttribute))
            select type;

EDIT: Moved from MemberInfo.GetCustomAttributes to Attribute.IsDefined based on Marc Gravell's suggestion.

Ani
  • 111,048
  • 26
  • 262
  • 307
  • 4
    Strictly speaking, Attribute.IsDefined(type, attribType) would be more efficient here – Marc Gravell Jan 31 '11 at 15:58
  • 3
    Might be type.IsDefined(attribType) - in which case, my mistake http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.isdefined.aspx – Marc Gravell Jan 31 '11 at 17:16
  • @Marc: I checked; this exists too. http://msdn.microsoft.com/en-us/library/system.attribute.isdefined.aspx – Ani Jan 31 '11 at 17:21
  • 1
    Was working on something similar today and din't occur to me to use LINQ for it. Very nice! – HAL9000 Feb 11 '11 at 20:51