It's not clear where do you want to find the type to be used in the generic, from what set of types. It's even less clear if such approach is reasonable or not. By some reasons, I doubt it.
However, the problem itself is technically simple. The only problems are: 1) what happens if you find more then one class? 2) where do you want to get the instance of the class? instantiate it?
However, let's assume that you already have some set of types, you stop search if you find the first of types which satisfy the criterion, and you want to instantiate the type when you find it, it would be pretty simple. Let's also assume you have some assembly where you want to find all the types it declares and return the instance of the first suitable type found. We will also need one more assumption: the type implementing
IAuditable
should have some certain signature. In my example, it will be the parameterless constructor (most usual case):
using System;
using System.Reflection;
static IAuditable FindFirstAuditable(Assembly assembly) {
Type[] types = assembly.GetTypes();
string interfaceName = typeof(IAuditable).FullName;
foreach (Type type in types) {
Type interfaceType = type.GetInterface(interfaceName, false);
if (interfaceType == null) continue;
ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
if (constructor == null) continue;
return (IAuditable)constructor.Invoke(null);
}
return null;
}
If you want just the type, you can return the type instead, of you can call
GetType()
on the object you have.
As you can see, too many assumptions. Also, it could be slow. But this is because your goals are not clear enough. I hope it will be enough for you to understand what techniques you could use and do it in your way. And I would recommend you to seriously review your approach.
—SA