views:

70

answers:

1

Here is what I have.

BaseClass<T>
{
}

MyClass
{
}

NewClass : BaseClass<MyClass>
{
}

I need to see if there is a class that implements the BaseClass with the specific generic implementation of MyClass and get the type of that class. In this case it would be NewClass

Edit

AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(
typeof(BaseClass<>).MakeGenericType(typeof(MyClass)).IsAssignableFrom);

This returns a list of all types that implement BaseClass< MyClass >.

Thanks

+2  A: 

If you have a list of types (called types) that you want to test, you can get all types that inherit from the specified base class using IsAssignableFrom method:

var baseType = typeof(BaseClass<MyClass>);
var info = types.Where(t => baseType.IsAssignableFrom(t)).FirstOrDefault();
if (info != null) 
  // We have some type 'info' which matches your requirements

If you have only runtime information about the MyClass type then you can get the baseType like this:

Type myClassInfo = // get runtime info about MyClass
var baseTypeGeneric = typeof(BaseClass<>);
var baseType = baseTypeGeneric.MakeGenericType(myClassInfo);

You wrote that you need to find the class somehow, so the last question is how to get the list types. To do that, you'll need to search some assemblies - you can start with currently executing assembly (if the type is in your application) or with some well-known assembly identified by the name.

// Get all types from the currently running assembly
var types = Assembly.GetExecutingAssembly().GetTypes();

Unfortunately, there is no way to "magically" find some type like this - you'll need to search all available types, which may be quite an expensive operation. However, if you need to do this only once (e.g. when the application starts), you should be fine.

Tomas Petricek
Thanks. I was checking for typeof(BaseClass<>) and forgetting to add the MakeGenericType call.
Robin Robinson