Is it possible for the a.doStuff() method to print \"B did stuff\" without editing the A class? If so, how would I do that?
class Program
{
static void Main
The code for class A & B you have posted will anyways generate below compiler warning and will ask to use the new
keyword on class B, although it will compile:
The keyword new is required on 'B.doStuff()' because it hides inherited member 'A.doStuff()'
Use method hiding
along with new
and virtual
keyword in class Mapper and class B as follows:
class Program
{
static void Main(string[] args)
{
Mapper a = new B(); //notice this line
B b = new B();
a.doStuff();
b.doStuff();
Console.ReadLine();
}
}
class A
{
public void doStuff()
{
Console.WriteLine("A did stuff");
}
}
class Mapper : A
{
new public virtual void doStuff() //notice the new and virtual keywords here which will all to hide or override the base class implementation
{
Console.WriteLine("Mapper did stuff");
}
}
class B : Mapper
{
public override void doStuff()
{
Console.WriteLine("B did stuff");
}
}