Virtual functions are not specific to C#. They allow algorithms, implemented to operate on objects of certain base class Parent
, to continue functioning on objects of class Child
, derived from class Parent
, without knowing Child
's implementation details.
A simple example: Object.ToString. We may have a form with various controls. If we want to check what controls we have, we could do:
foreach (control in form.Controls)
Debug.Print(control.ToString())
Each control belongs to a certain class which always has Object
class in its ancestry tree, and can override ToString
to provide its own meaningful implementation of it. However, we don't need to know the implementation details of ToString
of each control class we use on the form, to make this work. We don't even need to know if ToString
has been overridden or not.
Sometimes, designers of class libraries deliberately mark a class method as virtual, even though the default method implementation is expected to be quite generic at the first glance. That's done for future flexibility. This might be the case with your public virtual ICollection<Order> Orders { get; set; }
example. A developer who may be deriving a new class from the Client
class in the future will have an option to provide an alternative behavior for Orders
property. The code in the base library which, for example, is responsible for processing orders, will continue to work correctly with such new classes, on the binary level. There will be no need to recompile the base library.