I have a collection ot types:
List<Type> types;
And I want to find out which of these types inherit from a concrete generic class without caring about T:
public class Generic<T>
I've tried with:
foreach(Type type in types)
{
if (typeof(Generic<>).IsAssignableFrom(type))
{
....
}
}
But always returns false, probably due to generic element. Any ideas?
Thanks in advance.
AFAIK, no types report as inheriting from an open generic type: I suspect you'll have to loop manually:
static bool IsGeneric(Type type)
{
while (type != null)
{
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(Generic<>))
{
return true;
}
type = type.BaseType;
}
return false;
}
Then the sub-list is:
var sublist = types.FindAll(IsGeneric);
or:
var sublist = types.Where(IsGeneric).ToList();
or:
foreach(var type in types) {
if(IsGeneric(type)) {
// ...
}
}
You should get first generic ancestor for the particular type in your list, and then compare generic type definition with Generic<>
:
genericType.GetGenericTypeDefinition() == typeof(Generic<>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With