Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an interface extends another in C#?

The Type.IsSubclassOf method only works with two concrete types, e.g.

public class A {}
public class B : A {}
typeof(B).IsSubclassOf(typeof(A)) // returns true

Is there a way to find out if an interface extends another? e.g.

public interface IA {}
public interface IB : IA {}

The only thing I can think of is to use GetInterfaces on IB and check if it contains IA, does anyone know of another/better way to do this?

like image 686
theburningmonk Avatar asked Oct 08 '10 17:10

theburningmonk


People also ask

Can interface extend another interface example?

An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. The following Sports interface is extended by Hockey and Football interfaces.

Can a interface extend inherit another interface?

An interface can extend other interfaces, just as a class subclass or extend another class.

How can you tell if an object implements an interface?

Use a user-defined type guard to check if an object implements an interface in TypeScript. The user-defined type guard consists of a function, which checks if the passed in object contains specific properties and returns a type predicate.

What happens when you extend an interface?

An interface is a contract without implementations (Java8 introduced default methods). By extending you extend the contract with new "names" to be implemented by concrete class.


2 Answers

You can do

bool isAssignable = typeof(IA).IsAssignableFrom(typeof(IB));

which gives you the information you need in this case I guess, but also of course works not only for interfaces.

I assume you have Type objects, if you have actual instances, this is shorter, clearer and more performant:

public interface ICar : IVehicle { /**/ }

ICar myCar = GetSomeCar();
bool isVehicle = myCar is IVehicle;
like image 138
herzmeister Avatar answered Oct 01 '22 07:10

herzmeister


IsAssignableFrom is what you are looking for. It's the equivalent of the is operator but with runtime values as types.

Examples:

// Does IDerivedInterface implements IBaseInterface ?
bool yes = typeof(IBaseInterface).IsAssignableFrom(typeof(IDerivedInterface));

// Does instance implements IBaseInterface ?
bool yes = typeof(IBaseInterface).IsAssignableFrom(instance.GetType());
like image 20
Coincoin Avatar answered Oct 01 '22 09:10

Coincoin