Resources » .NET programming » .NET Framework

How Method Hiding is helpfull to development.


Last Updated:   Category: .NET Framework    
Author: Member Level: Gold    Points: 15


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()"
}
}
}


Did you like this resource? Share it with your friends and show your love!

Responses to "How Method Hiding is helpfull to development."

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

Feedbacks      

Post 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:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India