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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With