Search code examples
c#.netoopinheritancepolymorphism

method hiding in c# with a valid example. why is it implemented in the framework? what is the Real world advantage?


Can anyone explain the actual use of method hiding in C# with a valid example ?

If the method is defined using the new keyword in the derived class, then it cannot be overridden. Then it is the same as creating a fresh method (other than the one mentioned in the base class) with a different name.

Is there any specific reason to use the new keyword?


Solution

  • C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

        using System;
        namespace Polymorphism
        {
            class A
            {
                public void Foo() { Console.WriteLine("A::Foo()"); }
            }
    
            class B : A
            {
                public new void Foo() { Console.WriteLine("B::Foo()"); }
            }
    
            class Test
            {
                static void Main(string[] args)
                {
                    A a;
                    B b;
    
                    a = new A();
                    b = new B();
                    a.Foo();  // output --> "A::Foo()"
                    b.Foo();  // output --> "B::Foo()"
    
                    a = new B();
                    a.Foo();  // output --> "A::Foo()"
                }
            }
        }