cannot understand what method hiding exactly do 'behind the scenes'

39 Views Asked by At

i find it hard to understand exactly what method hiding does. can somebody please explain me what is going on 'behind the scenes' while using method hiding?

    class Base
   {
      public virtual void OverrideMethod()
        {
          Console.WriteLine("Base.OverrideMethod");
        }
      public virtual void HideMethod()
        {
          Console.WriteLine("Base.HideMethod");
        }
   }

    class Derived:Base
   {
      public override void OverrideMethod()
        {
          Console.WriteLine("Derived.OverrideMethod");
        }
      public new void HideMethod()
        {
          Console.WriteLine("Derived.HideMethod");
        }
   }

(1) what does this really do?

    Base x=new Derived();

(2) what does these really do?

    x.OverrideMethod();
    x.HideMethod();

thank you in advance :)

1

There are 1 best solutions below

0
Christopher On BEST ANSWER

There is hiding and there is overriding. Both are opposites. Personally I keep forgetting hiding aside from thinking "this is not overriding, better not to mix those up". I can not remember a single case where I used it. If I ever can not override, I just encapsulate rather then deal with hiding. So it might well be one of those things someone thought up way back, but never quite took tracktion.

Overriding changes the implementation. It must be explicitly allowed by the baseclass (virtual). It must explicitly be done by the derived class. But in turn the override takes precedence even if class is cast to a base type. Example: Object.ToString(). Code like Console.WriteLine has overloads that just accept a bunch of Objects. But since you can not print Objects, it jsut calls it's ToString() Method.

Hiding does not change the Implementation. It only hides it. As long as you do not cast it to a more basic type, you will have the Hiding Implementation hide the baseclass one. But once you cast down, the baseclass implementation asserts itself. In turn no "allowance" is nessesary.