What is Shadowing?

james picture james · Mar 23, 2009 · Viewed 57.5k times · Source

In C# what does the term shadowing mean? I have read this link but didn't fully understand it.

Answer

Jim Mischel picture Jim Mischel · Mar 23, 2009

Shadowing hides a method in a base class. Using the example in the question you linked:

class A 
{
   public int Foo(){ return 5;}
   public virtual int Bar(){return 5;}
}
class B : A
{
   public new int Foo() { return 1;}
   public override int Bar() {return 1;}
}

Class B overrides the virtual method Bar. It hides (shadows) the non-virtual method Foo. Override uses the override keyword. Shadowing is done with the new keyword.

In the code above, if you didn't use the new keyword when defining the Foo method in class B, you would get this compiler warning:

'test.B.Foo()' hides inherited member 'test.A.Foo()'. Use the new keyword if hiding was intended.