Mixing inherited classes and interfaces
Hello,
a former c++ dev in my team is a bit worried by the following code which implies inheriting interfaces, and having inheriting implementations as well.
| |
publicinterface IMyInterface { /* */ }publicinterface IMyChildInterface : IMyInterface { /* */ } publicclass MyImpl : IMyInterface { /* */ } publicclass MyChildImpl : MyImpl, IMyChildInterface { /* */ }
|
Does anyone see any potential issue with manipulating the objects through the interfaces here ?
regards
Thibaut
That's fine. MyChildImpl won't be able to re-implement any members from IMyInterface anyway unless it explicitly implements it.
The thing you have to remember is interface members are implicitly virtual. So if for example you had the following code:
| |
public interface IMyInterface { void Method1(); } public interface IMyChildInterface : IMyInterface { void Method2(); } public class MyImpl : IMyInterface { void IMyInterface.Method1() { Console.WriteLine("Method1"); } } public class MyChildImpl : MyImpl, IMyInterface, IMyChildInterface { void IMyInterface.Method1() { Console.WriteLine("ChildMethod1"); } void IMyChildInterface.Method2() { Console.WriteLine("ChildMethod2"); } } |
Running the following code:
| | MyChildImpl child = new MyChildImpl(); ((IMyChildInterface)child).Method1(); ((IMyInterface)child).Method1(); |
would output
ChildMethod1
ChildMethod1