Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 933
James Wiseman Avatar asked Feb 26 '10 15:02

James Wiseman


2 Answers

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.

like image 77
kemiller2002 Avatar answered Nov 16 '22 13:11

kemiller2002


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();
like image 45
Mark Seemann Avatar answered Nov 16 '22 15:11

Mark Seemann