I am trying to understand new
virtual
method.
What are the differences between the following two ways:
define a method in a base class without
virtual
, and define a method with the same name and signature in a subclassdefine a method in a base class with
virtual
, and define a method with the same name and signature andnew
in a subclass?
If they differ, why in the following example do they behave the same?
using System;
public class Base
{
public void DoIt()
{
Console.WriteLine ("Base: DoIt");
}
public virtual void DoItVirtual1()
{
Console.WriteLine ("Base: DoItVirtual1");
}
public virtual void DoItVirtual2()
{
Console.WriteLine ("Base: DoItVirtual2");
}
}
public class Derived : Base
{
public void DoIt()
{
Console.WriteLine ("Derived: DoIt");
}
public override void DoItVirtual1()
{
Console.WriteLine ("Derived: DoItVirtual1");
}
public new void DoItVirtual2()
{
Console.WriteLine ("Derived: DoItVirtual2");
}
}
class MainClass {
public static void Main (string[] args) {
Base b = new Base();
Derived d = new Derived();
Base bd = new Derived();
b.DoIt();
d.DoIt();
bd.DoIt();
b.DoItVirtual1();
d.DoItVirtual1();
bd.DoItVirtual1();
b.DoItVirtual2();
d.DoItVirtual2();
bd.DoItVirtual2();
}
}
Output:
Base: DoIt
Derived: DoIt
Base: DoIt
Base: DoItVirtual1
Derived: DoItVirtual1
Derived: DoItVirtual1
Base: DoItVirtual2
Derived: DoItVirtual2
Base: DoItVirtual2