0

If I have a .Net assembly loaded and I want to use reflection to find the classes (types) decorated with some attribute, eg

[MyClassAttribute]
public SomeClass
{
} 

how do I do it in C#? I have got as far as

Assembly assy = Assembly.Load(assyPath);
var classesInAssy = assy.GetTypes();

but thereafter I'm stumped. I now know I have to use the CustomAttibutes collection on the type, but I'm using VS2013 Pro (which includes unit testing), and the attribute in question isn't one of mine but the MS TestClass attribute. However I can't seem to reference the assembly it is defined in (Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll) even though the dll is listed in the Add References dialog in VS2013. Am I missing something?

TIA,

haughtonomous
  • 4,602
  • 11
  • 34
  • 52

1 Answers1

0

An alternative to Jon Skeet's answer is to use GetCustomAttributes:

Type[] classesWithAttr = assy.GetTypes()
    .Where(t => t.GetCustomAttributes(typeof(MyClassAttribute), false).Length > 0)
    .ToArray();
Jashaszun
  • 9,207
  • 3
  • 29
  • 57