Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all types from an assembly derived from a base class

Tags:

c#

reflection

I am trying to examine the contents of an assembly and find all classes in it that are directly or indirectly derived from Windows.Forms.UserControl.

I am doing this:

Assembly dll = Assembly.LoadFrom(filename);
var types = dll.GetTypes().Where(x => x.BaseType == typeof(UserControl));

But it is giving an empty list because none of the classes directly extend UserControl. I don't know enough about reflection to do it quickly, and I'd rather not write a recursive function if I don't have to.

like image 989
captncraig Avatar asked Mar 19 '10 21:03

captncraig


2 Answers

You should use Type.IsSubclassOf this instead:

var types = dll.GetTypes().Where(x => x.IsSubclassOf(typeof(UserControl)));
like image 95
Fredrik Mörk Avatar answered Oct 31 '22 11:10

Fredrik Mörk


You can use :

    var assembly = Assembly.Load(filename);
    var types = assembly.GetTypes().Where((type) => typeof(UserControl).IsAssignableFrom(type));
like image 1
Islam Yahiatene Avatar answered Oct 31 '22 10:10

Islam Yahiatene