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 }
A class implements an interface if it declares the interface in its implements clause, and provides method bodies for all of the interface's methods. So one way to define an abstract data type in Java is as an interface, with its implementation as a class implementing that interface.
To declare a class that implements an interface, include an implements keyword in the class declaration.
Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.
C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.
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.
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