I have 2 interfaces and 2 classes that I investigate via Reflection:
- IParent
- IChild – derives from IParent
- Parent
- Child – derives from Parent
Strange thing for me is the fact that when I look through reflection on IChild type I don’t find IParent method.
Same code applied to Child type works as expected – reflection shows Parent method.
interface IParent
{
void ParentMethod();
}
interface IChild : IParent
{
void ChildMethod();
}
class Parent
{
public void ParentMethod(){}
}
class Child : Parent
{
public void ChildMethod(){}
}
void Main()
{
//investigate derived interface
Type t = typeof(IChild);
var info = t.GetMethod("ChildMethod");//ok
Console.WriteLine(info);
info = t.GetMethod("ParentMethod");//returns null!
Console.WriteLine(info);
//investigate derived class
t = typeof(Child);
info = t.GetMethod("ChildMethod");//ok
Console.WriteLine(info);
info = t.GetMethod("ParentMethod");//ok
Console.WriteLine(info);
}
Please explain such behaviour?
Is there any workaround to reflect base interface’s methods from the derived interface’s type?
Although, we use the interfaces as the same way we use inheritance (“:”); interfaces are not inherited; they are to be implemented. In such a case; inheritance is confused with implementation since they are defined using the same operator (“:”).
As a summary;
IA : IBandA:IAmeans; any class implementing IA, shall implement IB. In this case; A shall implement IA and IB.A:Bmeans A class inherits B class; it does not implement.The confusion here derives from using the same operator (“:”).
Check this page interface inheritance