Filtering GetExportedTypes() question

I need to filter out only classes that derive from a given generic base type from an assembly. I will not know before hand what these will be.

Assume base type of BaseThing<T>.

Here’s what I currently have (after googling and banging my head). No matter what I do, it’s either empty or throws an exception.

[COLOR=#0000ff]var types = assembly.GetExportedTypes().Where(x => typeof[FONT=Consolas][SIZE=2][FONT=Consolas][SIZE=2]COLOR=#000000.IsAssignableFrom(x));[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT]

Please tell me what I’m doing wrong?

Hmmm. It sure looks right. What’s the error?

The resulting collection is empty.


Upon further testing I found that IsAssignable does not work as expected. Given the following three simple classes…

public class Thing<T> { }
public class Sample { }
public class SampleThing : Thing<Sample> { }

… the following results are found…

Type baseType = typeof(Thing<>);
Type testType = typeof(SampleThing);
Bool assignable = baseType.IsAssignableFrom(testType);
// assignable is false!

I need another method of querying this.

Solution found!

The problem is that SampleThing derives from Thing<Sample> not Thing<>. The two are considered different beasts. The only way to get around this is to use a recursive method like the one below.

public bool IsDerivedFromGenericType(Type givenType, Type genericType)
Type baseType = givenType.BaseType;
if (baseType == null)
return false;
if (baseType.IsGenericType)
if (baseType.GetGenericTypeDefinition() == genericType)
return true;
return IsDerivedFromGenericType(baseType, genericType);

And then use it like this…

var types = Assembly.GetExecutingAssembly().GetExportedTypes().Where(x => IsDerivedFromGenericType(x, typeof(Thing<>)));