I found this behaviour while working with a third-party library where I needed to hide and change one of it’s 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 is it that when I run the following:
var i = (IBaseInterface) (new ChildClass());
Console.WriteLine(i.MethodToHide());
the output is
BaseClass
, but when changing the ChildClass signature to
class ChildClass : BaseClass, IBaseInterface
, the output is
ChildClass
Why do I need to explicitly specify the interface for the BaseClass method to be hidden by the ChildClass?
You need to read a bit more about the difference between overriding and hiding:
Link: Override versus Hide
In a nutshell:
Hiding (using the new) runs the method according to the variable’s type.
Overriding overrides the method and will only use the child’s method.
Edit:
When you use an Interface variable:
The compiler will search for the best match for the methods that are used by the interface.
Because you declared the BaseClass to implement the interface, then its methods will be chosen.
If the ChildClass doesn’t explicitly implement the interface, then the compiler can’t link the methods to the interface. By its point of view the BaseClass just happens to have methods by the same name.
When you explicitly declare that the ChildClass also implements the interface, then its methods will be the best choice.