Why does a child class need to implement a parent interface in order to hide one of these methods by parents in C #?

I found this behavior while working with a third-party library, where I needed to hide and change one of its methods.

I have the following setup:

interface IBaseInterface { string MethodToHide(); } class BaseClass : IBaseInterface { public string MethodToHide() { return "BaseClass"; } } class ChildClass : BaseClass { new public string MethodToHide() { return "ChildClass"; } } 

Why am I running the following:

 var i = (IBaseInterface) (new ChildClass()); Console.WriteLine(i.MethodToHide()); 

output

Baseclass

but when changing ChildClass signature to

 class ChildClass : BaseClass, IBaseInterface 

output

Childclass

Why do I need to explicitly specify an interface for the BaseClass method that ChildClass should hide?

+4
source share
3 answers

You need to read a little more about the difference between overriding and hiding :

Link: Override versus Hide

In a nutshell:

Hiding (using the new one) starts the method according to the type of variable.
Overriding overrides the method and will only use the child method.

Edit

When using an interface variable:

 var i = (IBaseInterface) (new ChildClass()); 

The compiler will look for the best match for the methods used by the interface.
Since you declared BaseClass to implement the interface, its methods will be selected.

If ChildClass does not explicitly implement the interface, then the compiler cannot associate methods with the interface. In his opinion, BaseClass just has methods with the same name.

When you explicitly declare that ChildClass also implements the interface, its methods will be the best choice.

+4
source

You should mark MethodToHide as virtual in your BaseClass. Then your ChildClass can override it. See http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx for more details.

I believe this is an important part of the specification:

10.6.3 Virtual Methods . When invoking a virtual method, the type of execution time of the instance for which it is invoking the implementation of the actual method invocation. In a non-virtual method call, the type of compilation time instance is a determining factor.

So, when you throw your source object on an IBaseInterface. It determines that the type is a BaseClass, since the one that implements it calls its method. In the second example, it resolves its ChildClass and calls its method.

+2
source

Because the main class implements the interface. A child class simply defines a new method that has nothing to do with the interface. In fact, the child class hides the method - what the "new" does.

+1
source

Source: https://habr.com/ru/post/1343357/


All Articles