views:

34

answers:

2

Hi,

How can I find every occurrence of a custom attribute inside an assembly?

If can find all types from an assembly where the attribute is used but thats not enough. How about methods, properties, enum, enum values, fields etc.

Is there any shortcut for doing this or is the only way to do it to write code to search all parts of a type (properties, fields, methods etc.) ?

Reflector does this, not sure how its implemented though.

+1  A: 

You can use Type.GetMembers() to get all members (properties, methods, fields etc) rather than doing each kind of member separately. That should at least make it somewhat simpler.

Note that you may well want to pass in various binding flags (instance, static, public, non-public) to make sure you catch everything.

Jon Skeet
Do I get Enum-values too? Not the enum itself but the values?
Marcus
@Marcus, enums are types, so you need to first get all types in the assembly using the `GetTypes` method and then apply the `GetMembers` method on each type. You will need two nested loops.
Darin Dimitrov
@Marcus: GetMembers() will return fields, and the values of enum types are fields.
Jon Skeet
@Darin, yeah I get that, so I have to manually check if the current member is an enum and then "query" it's enum values to also check those for attributes?
Marcus
@Jon, thanks that will work.
Marcus
@Marcus, no you don't need to check if it is an enum. You shouldn't care about this. As @Jon said, if the current type is an enumeration the `GetMembers()` method will return you the fields of this enum so that you can check if they are decorated with your custom attribute.
Darin Dimitrov
+4  A: 
assembly.GetTypes()
    .SelectMany(x => x.GetMembers())
    .Union(assembly.GetTypes())
    .Where(x => Attribute.IsDefined(x, attributeType));

(this will return enum values too since those are just public static fields under the hood. also, if you want private members, you'll have to tweak the BindingFlags you pass in)

Kirk Woll