theburningmonk
theburningmonk

Reputation: 16071

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?

Upvotes: 6

Views: 2270

Answers (2)

herzmeister
herzmeister

Reputation: 11297

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;

Upvotes: 12

Coincoin
Coincoin

Reputation: 28616

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());

Upvotes: 1

Related Questions