Nickon
Nickon

Reputation: 10146

Get all derived types of an abstract class within all the assemblies

I have a library that has an abstract class inside - suppose MyAbstractClass. This library is being used by some other projects (one app) within one solution.

I want to get all these classes. I created sample Program project and Program.Library that contains MyAbstractClass.

I have created two test classes derived from MyAbstractClass. One in the first project (Test1Class) and one in the second one (Test2Class).

I tried this code to find what I want:

var list = Assembly.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
                                .Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof (MyAbstractClass)));

It worked but found only Test1Class (because - I guess - it's placed in the same assembly as the executed code presented above?). I don't know how to find all the derived classes within all the assemblies in my whole app.

I have also tried:

var list = Assembly.GetAssembly(typeof(MyAbstractClass)).GetTypes()
                                .Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof (MyAbstractClass)));

But this one gives me an empty collection...

Upvotes: 1

Views: 107

Answers (2)

Gian Paolo
Gian Paolo

Reputation: 4249

You need to be sure that all assemblies you want to look in are already loaded when you call Assembly.CurrentDomain.GetAssemblies(); An Assembly get loaded when the runtime need it (i.e. when your program reach a point in your code that "use" that assembly, or if you specifically call a Assembly.Load or Assembly.LoadFile or whatever method you can use to explicitly load it

Upvotes: 1

Don
Don

Reputation: 6852

The problem is CurrentDomain.GetAssemblies() only lists the Assemblies currently loaded in your Application Domain. If you want to get the types in all assemblies in your application, then you need to ensure (somehow) that all assemblies are loaded.

One way of loading the assemblies manually is to use the following line of code:

var assembly = Assembly.LoadFile(@filename)

You'd need to do the above for each file, and then you can use the method CurrentDomain.GetAssemblies().

Upvotes: 1

Related Questions