Check if 'T' inherits or implements a class/interface
There is a Method called Type.IsAssignableFrom().
To check if T
inherits/implements Employee
:
typeof(Employee).IsAssignableFrom(typeof(T));
If you are targeting .NET Core, the method has moved to TypeInfo:
typeof(Employee).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo())
Note that if you want to constrain your type T
to implement some interface or inherit from some class, you should go for @snajahi's answer, which uses compile-time checks for that and genereally resembles a better approach to this problem.
You can use constraints on the class.
MyClass<T> where T : Employee
Take a look at http://msdn.microsoft.com/en-us/library/d5x73970.aspx
If you want to check during compilation: Error if if T
does NOT implement the desired interface/class, you can use the following constraint
public void MyRestrictedMethod<T>() where T : MyInterface1, MyInterface2, MySuperClass
{
//Code of my method here, clean without any check for type constraints.
}
I hope that helps.
The correct syntax is
typeof(Employee).IsAssignableFrom(typeof(T))
Documentation
Return Value:
true
ifc
and the currentType
represent the same type, or if the currentType
is in the inheritance hierarchy ofc
, or if the currentType
is aninterface
thatc
implements, or ifc
is a generic type parameter and the currentType
represents one of the constraints ofc
, or ifc
represents a value type and the currentType
representsNullable<c>
(Nullable(Of c)
in Visual Basic).false
if none of these conditions aretrue
, or ifc
isnull
.
source
Explanation
If Employee IsAssignableFrom T
then T
inherits from Employee
.
The usage
typeof(T).IsAssignableFrom(typeof(Employee))
returns true
only when either
-
T
andEmployee
represent the same type; or, -
Employee
inherits fromT
.
This may be intended usage in some case, but for the original question (and the more common usage), to determine when T
inherits or implements some class
/interface
, use:
typeof(Employee).IsAssignableFrom(typeof(T))