«^»
9.2. Overriding virtual methods

Suppose we have:

Figure tF = new Figure(100, 200);
tF.Fred();

In both Java and C#, it is the Fred method of the Figure class that will get called.

However, what happens if we have:

Figure tC = new Circle(100, 200, 50);
tC.Fred();

Assuming that Figure and Circle both declare a method called Fred, whose Fred method gets executed: is it Figure's Fred or Circle's Fred?

In Java, it is Circle's Fred that gets executed because tC is pointing to a Circle. This is known as dynamic binding.

However in C# (and also in C++), what happens depends on whether the declaration of Fred in the base class (Figure) includes the keyword virtual, i.e., does it use:

public void Fred() ...

or:

public virtual void Fred() ...

If virtual is absent, i.e., Fred is a non-virtual method, the declaration of Fred in Circle must include the keyword new, i.e.:

public new void Fred() ...

and the call tC.Fred() calls Figure's Fred.

If virtual is present, i.e., Fred is a virtual method, then:

  1. either the declaration of Circle's Fred includes the keyword new, i.e.:

    public new void Fred() ...
    

    and tC.Fred() calls Figure's Fred;

  2. or the declaration of Circle's Fred includes the keyword override, i.e.:

    public override void Fred() ...
    

    and tC.Fred() calls Circle's Fred.

Summary:

call of           virtual in       non-virtual in          absent
tC.Fred           base class         base class        in base class

absent in           warning            warning              error
derived class

new in              Figure             Figure              warning
derived class

override in         Circle              error               error
derived class