What is method hiding in C#.

You not only can override method, but also hide it. Basically, if method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword.

 

using System;

namespace CsharpConsoleApplication
{
    class A
    {
        public void Foo() { Console.WriteLine("A::Foo()"); }
    }

    class B : A
    {
        public new void Foo() { Console.WriteLine("B::Foo()"); }
    }

    internal class Program
    {
        private 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()"
        }
    }
}
Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this