ppiotrowicz
ppiotrowicz

Reputation: 4614

C# interface inheritance

Given:

public interface IA
{
    void TestMethod();
}

public interface IB : IA
{
}

Why:

typeof(IB).GetMethods().Count() == 0;

?

Just to be clear:

public class A
{
    public void TestMethod()
    {
    }
}

public class B : A
{
}

typeof(B).GetMethods().Count();

does work (it returns 5);

As a bonus:

typeof(IB).BaseType == null

Upvotes: 17

Views: 3867

Answers (4)

Kristof DB
Kristof DB

Reputation: 42

You have to define some Bindingflags into GetMethods().

Try

typeof(IB).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Count();

Upvotes: -1

Manfred
Manfred

Reputation: 5666

Here is the code for getting the counts for both IA and IB:

var ibCount = typeof(IB).GetMethods().Count(); // returns 0
var iaCount = typeof (IB).GetInterfaces()[0].GetMethods().Count(); // return 1

Note that in production code I wouldn't use GetInterfaces()[0] as typically in the code where I would use this I can't assume that I will always have at least one interface.

I also tried out the bindingflags as follows:

const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
var ibCount = typeof(IB).GetMethods(bindingFlags).Count();

However, this will still return 0 as interface IB still doesn't implement method TestMethod(). Interface IA does. Using binding flags would work if both IA and IB were classes. In that case however, you get a return value of 5. Don't forget that IA implicitly derives from class Object!

Upvotes: 13

Tormod
Tormod

Reputation: 4573

Consider IA to be an interface of IB, not its base.

Upvotes: 3

Matthew Abbott
Matthew Abbott

Reputation: 61589

This seems to be the design of the GetMethods function. It doesn't support inherited members in interfaces. If you want to discover all the methods, you need to query each interface type directly.

Check out the community content section of this MSDN article.

Upvotes: 10

Related Questions