Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all occurrences of a custom attribute in assemblies?

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.

like image 821
Marcus Avatar asked Dec 12 '25 05:12

Marcus


1 Answers

Do,

assembly.GetTypes()
    .SelectMany(type => type.GetMembers())
    .Union(assembly.GetTypes())
    .Where(type => Attribute.IsDefined(type, 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.

like image 169
Kirk Woll Avatar answered Dec 14 '25 17:12

Kirk Woll