Saturday, January 21, 2006 - Posts

Using IsSubclassOf on an Interface type

Well here's one that got me. The x.IsSubclassOf method tells you whether the passed-in type is derived from x. Sounds simple enough. Yet what isn't so obvious is if x is an interface type.

If you want to know if one interface derives from another interface, unlike class types you cannot use IsSubclassOf.

Take this example:

public interface IHaveLimbs
{
    void WaveLimbs();
}

public interface IHaveArms : IHaveLimbs
{
    IHand GetRightHand();
    IHand GetLeftHand();
}

In this case, running typeof(IHaveArms).IsSubclassOf(typeof(IHaveLimbs)) actually returns false.

Instead you have to test to see if IHaveArms implements the interface IHaveLimbs.

That sounds confusing, but it's probably because .Net only supports single inheritance. Because an interface can inherit from multiple interfaces, internally they're probably not inheriting at all - instead the interfaces are implementing other interfaces.

So there are really two ways to determine if one interface derives from another.

  • One way is to run typeof(IHaveArms).GetInterfaces() which returns all interfaces IHaveArms derives from (ie. the type of IHaveLimbs), and check it that way.
  • Another, simpler way, is to use typeof(IHaveArms).IsAssignableFrom(typeof(IHaveLimbs)) which returns true because IHaveLimbs can be assigned to an IHaveArms type.