Shadow inherited members
In this chapter you will learn:
Member shadow
During the inheritance we may shadow the members from the parent class. For example,
class Shape{/*from j ava2 s .c om*/
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{/* j a va 2 s . c om*/
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;//from j a va 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:
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class