Color Of Code

Font Size

SCREEN

Profile

Layout

Menu Style

Cpanel

C# Virtual function chain

The keywords in the virtual chain

  • abstract         - start of a virtual chain (without implementation)
  • virtual          - start of a virtual chain (with an implementation)
  • override         - override of a virtual or abstract method
  • sealed override  - end of the virtual chain (forbids further overrides)
  • new virtual      - begin of a new virtual chain

Variants of chains

Let A, B, C be classes that derive from each other in that order (A is the base class). There are several different chains possible:

  • Yellow means the classes can be instanciated
  • Blue means the class is abstract (cannot be instanciated)
  • Green shows optional overrides

With the new virtual keyword one can start a new virtual chain (not recommended as it can be misleading). New without virtual creates a new non-virtual method, what is another option that is not recommended either. Always prefer using distinct names for distinct things.

With sealed override, you can prevent further overriding in derived classes. Sealed also requires the override keyword

Increased robustness against changes

What makes this implementation special is its robustness. If you happen to modify the signature of the virtual method, you will get errors if you forget to adjust the overriding methods. This differs from C++ for example where there is only the virtual keyword and can produce silently runtime problems. In C# you'll detect this at compile time. Java implements the override as an annotation and every method is virtual by default...

Example

Taken from ECMA-334: http://en.csharp-online.net/ECMA-334:_17.5.6_Abstract_methods

public abstract class Shape
{
public abstract void Paint(Graphics g, Rectangle r);
}
public class Ellipse: Shape
{
public override void Paint(Graphics g, Rectangle r) {
g.DrawEllipse(Pens.Black, r);
}
}
public class Box: Shape
{
public override void Paint(Graphics g, Rectangle r) {
g.DrawRectangle(Pens.Black, r);
}
}