I can think of two basic situations where you might want to hide a method inherited from a base class:
1. The method is non-virtual (which rules out overriding) but you want to replace the implementation with one which is appropriate to the derived class.
2. You want to change the accessibility of the inherited method (virtual or not) in the derived class.
In these two situations, you therefore need to hide the base class and (in the case of #1) replace it with your new one or (in the case of #2) change the accessibility but otherwise use the inherited implementation.
Here's an example which illustrates these situations:
using System;
public class Parent
{
public void A()
{
Console.WriteLine("Parent.A invoked");
}
public void B()
{
Console.Write("Parent.B invoked");
}
public virtual void C()
{
Console.Write("Parent.C invoked");
}
}
public class Child : Parent
{
new public void A() // situation #1
{
Console.WriteLine("Child.A invoked");
}
new internal void B() // situation #2
{
base.B();
Console.WriteLine(" but access changed to internal");
}
new protected internal void C() // also situation #2
{
base.C();
Console.WriteLine(" but access changed to protected internal");
}
}
class Program
{
static void Main()
{
Child c = new Child();
c.A();
c.B();
c.C();
Console.WriteLine();
Parent p = c;
p.A();
p.B();
Console.WriteLine();
p.C();
Console.ReadKey();
}
}
The output is:
Child.A invoked
Parent.B invoked but access changed to internal
Parent.C invoked but access changed to protected internal
Prasham SabadraRank #116 · 19.3K reputationPosted Mar 11, 2015, 12:37 AM EDT
Please check following links:
http://www.c-sharpcorner.com/UploadFile/8911c4/different-between-method-overriding-method-hiding-new-keyw/
http://stackoverflow.com/questions/1193848/method-hiding-in-c-sharp-with-a-valid-example-why-is-it-implemented-in-the-fram
VulpesRank #55 · 29.2K reputationPosted Mar 11, 2015, 12:54 PM EDT
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts