How Method Hiding is helpfull to development.


Method hiding in C# is similar to the function overriding feature in C++. Functions of the base class are available to the derived class. If the derived class is not satisfies, one of the functions available to it from the base class can define its own logic of the same function with the same function signature, just differing in implementation. This new definition hides the base class implementation.


using System;
namespace Polymorphism
{
class A
{
public void Siva() { Console.WriteLine("A:: Siva()"); }
}

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

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a. Siva(); // output --> "A:: Siva()"
b. Siva(); // output --> "B:: Siva()"

a = new B();
a. Siva(); // output --> "A:: Siva()"
}
}
}

Although the above code compiles and runs, the compiler produces a following warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Siva()' because it hides inherited member 'Polymorphism.A.Siva()'

Method Hiding :
After inheriting the base class into child class and you are defining for same method name(siva()) then compiler gives warning. If a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. This is called "Method hiding". The following example illustrates Method hiding.

using System;
namespace Polymorphism
{
class A
{
public void Siva() { Console.WriteLine("A::Siva()"); }
}

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

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Siva(); // output --> "A::Siva()"
b.Siva(); // output --> "B::Siva()"

a = new B();
a.Siva(); // output --> "A::Siva()"
}
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: