What is member shadow and how to avoid it in C#
Member shadow
During the inheritance we may shadow the members from the parent class. For example,
class Shape{//from w w w . j a v a 2s . c o m
int Width;
}
class Rectangle: Shape{
int Width;
}
The Width
from the Rectangle
shadows the Width
from Shape.
To mark the hidden fields C# uses new
modifier.
class Shape{/*from w w w . ja v a2 s. c o m*/
int Width;
}
class Rectangle: Shape{
new int Width;
}
new and virtual in member shadow
We can mark virtual member with new
keyword.
The different is shown in the following code.
using System;/* w w w.j ava 2 s. c o m*/
public class BaseClass
{
public virtual void MyMethod()
{
Console.WriteLine("BaseClass.MyMethod");
}
}
public class Overrider : BaseClass
{
public override void MyMethod() { Console.WriteLine("Overrider.MyMethod"); }
}
public class Hider : BaseClass
{
public new void MyMethod() { Console.WriteLine("Hider.MyMethod"); }
}
class Program
{
static void Main(string[] args)
{
Overrider over = new Overrider();
BaseClass b1 = over;
over.MyMethod();
Hider h = new Hider();
BaseClass b2 = h;
h.MyMethod();
}
}
The output: