Search code examples
c#.netinheritancemethod-hiding

Why can a method marked that is hiding an implementation in the base class call the hidden method?


I've been doing a little reading around the c# spec, and come across a scenario I didn't expect, and was hoping somebody could share some light.

I stumbled across the new keyword for hiding members of a base class within a derived class, and subsequently a few discussions over when to use new as opposed to an override on a virtual member.

I threw a little code sample in to my IDE, expecting to see a compilation error

public class BaseType
{
    public void method()
    {
        // do nothing
    }
}
public class DerivedType : BaseType
{
    public new void method()
    {
        base.method();
    }
}

but instead found this to be legal c#. Since the derived class has hidden the presence of method(), why am I still allowed to call it?

Cheers


Solution

  • The DerivedType is hiding the method from the classes which will be inheriting DerivedType, and not from itself.
    Note that, to hide the method, the class has to know there exists a method in it's parent class with the same name and same arguments. Hence a class hiding the method from it's own scope is logically incorrect.