user1229895 user1229895 - 1 month ago 6
C# Question

Check if 'T' inherits or implements a class/interface

Is there a way to test if T inherits/implements a class/interface?

private void MyGenericClass<T> ()
{
if(T ... inherits or implements some class/interface
}

Answer

There is a Method called Type.IsAssignableFrom().

It is used like this:

typeof(Employee).IsAssignableFrom(typeof(T));

If you are targeting .NET Core, the method has moved to TypeInfo:

typeof(Employee).GetTypeInfo().IsAssignableFrom(typeof(T))
Comments