Is there a way to test if T inherits/implements a class/interface?
private void MyGenericClass ()
{
if(T ... inherits or implements some class/i
Alternate ways to tell if an object o
inherits a class or implements an interface is to use the is
and as
operators.
If you want to only know if an object inherits a class or implements an interface, the is
operator will return a boolean result:
bool isCompatibleType = (o is BaseType || o is IInterface);
If you want to use the inherited class or implemented interface after your test, the as
operator will perform a safe cast, returning a reference to the inherited class or the implemented interface if compatible or null if not compatible:
BaseType b = o as BaseType; // Null if d does not inherit from BaseType.
IInterface i = o as IInterface; // Null if d does not implement IInterface.
If you have only the type T
, then use @nikeee's answer.
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))
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
If Employee IsAssignableFrom T
then T
inherits from Employee
.
The usage
typeof(T).IsAssignableFrom(typeof(Employee))
returns true
only when either
T
and Employee
represent the same type; or,Employee
inherits from T
.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))
I believe syntax is: typeof(Employee).IsAssignableFrom(typeof(T));
Although IsAssignableFrom is the best way as others have stated, if you only need to check if a class inherits from another, typeof(T).BaseType == typeof(SomeClass)
does the job too.
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