Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

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 } 
like image 959
user1229895 Avatar asked May 23 '12 10:05

user1229895


People also ask

How do you know if a class implements an 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.

Which keyword validates whether a class implements an interface?

To declare a class that implements an interface, include an implements keyword in the class declaration.

Can a class inherit a interface?

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.

Can you inherit an interface C#?

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.


1 Answers

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).Ge‌​tTypeInfo()) 

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.

like image 104
nikeee Avatar answered Sep 27 '22 17:09

nikeee