Mutation Person
Mutation Person

Reputation: 30520

Class Hierarchy for Interfaces C#

I'm playing around with some classes and interfaces, and have developed a simple method to determine the hierarchy of a class, i.e. to identify the chain of inheritance.

public static void OutputClassHierarchy(Type ty)
{
    if (ty.BaseType == null)
    {
        Console.WriteLine("{0}: Base", ty);
        Console.WriteLine("");
        return;
    }
    Console.WriteLine("{0} : {1}", ty, ty.BaseType);
    OutputClasshierarchy(ty.BaseType);
}

So, for

OutputClassHierarchy(typeof(System.Exception));

I get the output:

System.Exception : System.Object

System.Object : Base

Which is what I expect.

But, If I attempt the same with an Interface that implements another interface, i.e.

interface IMyInterface : IDisposable
{
    void Hello();
}

...

OutputClassHierarchy(typeof(IMyInterface));

I get the output:

MyNameSpace.IMyInterface : Base

So, what is going on here? Is it possible to infer the interface hierarchy as declared above, or is there no such thing when it comes to interfaces?

Also, where is System.Object in all of this? I thought everything was built upon it.

Upvotes: 5

Views: 3529

Answers (2)

kemiller2002
kemiller2002

Reputation: 115508

Interfaces are not derived from Object, so it won't show up when you output the base of it. Here is Eric Lippert's comment on things which derive from Object (and things which are convertable to type Object).

http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx

This SO answer may help answer your question about interfaces containing other interfaces:

How to get interface basetype via reflection?

Interfaces contain other interfaces, they don't derive from them so it won't show up when looking for it's base type.

Upvotes: 4

Mark Seemann
Mark Seemann

Reputation: 233197

An interface doesn't have a single base type, as it could implement several other interfaces, e.g.

public IMyInterface : IDisposable, IComponent

However, you can get at those interfaces by using the GetInterfaces method:

var interfaces = typeof(IMyInterface).GetInterfaces();

Upvotes: 4

Related Questions