Know the answer? Post it. Somebody with the same question will find it here.
VulpesRank #55 · 29.2K reputationPosted Mar 25, 2014, 10:50 AM EDT
0
Method shadowing means the hiding of a method in its base class by a method of the same name in a derived class.
In C#, method shadowing is more usually called method hiding.
The usual purpose of method shadowing is to prevent a base class method from being exposed as part of the public interface of the derived class.
Where you are unable to override a base class method (because it's not virtual) it's the only way you have for (in effect) replacing it with your own implementation.
However, the derived class still has internal access to the hidden method using the 'base' keyword and it is sometimes useful to simply supplement the base class implementation with some additional code.
Although not essential it's good practice to indicate to the compiler that you're hiding an inherited method by prefixing the derived class method with the 'new' keyword. If you don't do this, the compiler will issue a warning.
Here's a simple example of method shadowing:
using System;
class Parent
{
public void MyMethod()
{
Console.WriteLine("Hello from Parent.MyMethod");
}
}
class Child : Parent
{
new public void MyMethod() // shadows Parent method of same
name
{
base.MyMethod(); // calls base class method
Console.WriteLine("and hello also from Child.MyMethod");
Shadowing is concept of VB. Name suggest itself... It hides method in a base class.
class A { public int TestMethod(){ return 5;} public virtual int TestMethod1(){return 5;} } class B : A { public int TestMethod() { return 1;} public override int TestMethod1() {return 1;} }
here TestMethod of class B is shadow TestMethod of base class A.
VulpesRank #55 · 29.2K reputationPosted Mar 25, 2014, 10:50 AM EDT
The output is:
Jignesh TrivediRank #16 · 50.3K reputationPosted Mar 25, 2014, 9:18 PM EDT
Hi,
Shadowing is concept of VB.
Name suggest itself... It hides method in a base class.
class A
{
public int TestMethod(){ return 5;}
public virtual int TestMethod1(){return 5;}
}
class B : A
{
public int TestMethod() { return 1;}
public override int TestMethod1() {return 1;}
}
here TestMethod of class B is shadow TestMethod of base class A.
hope this will help you.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts