Inheritance modifiers
Virtual
Has default implementation in the base class. Virtual method is overridden by sub classes in order to provide specialized implementation. Methods, properties, indexers, and events can all be declared virtual. Subclass override a virtual method by applying the override modifier. The signatures, return types, and accessibility of the virtual and overridden methods
must be identical. An overridden method can call its base class implementation via the base keyword. Calling virtual methods from a constructor is potentially dangerous.
The virtual modifier tells the compiler that when any class derived from class A is used, an override method should be called.
virtual members cannot be private and virtual method is overwritten with the keyword override.
Why need virtual methods?
Sometimes we are not aware of all the types of objects that will occur when executed. It is better to re-implement functionality depending on the more specific types.
Instance and static methods are faster to invoke than interface and virtual methods.
namespace Rextester { public class Program { public static void Main(string[] args) { House mansion = new House { Name="McMansion", Mortgage=250000 }; Console.WriteLine (mansion.Liability); // 250000 } } public class Asset { public string Name; public virtual decimal Liability => 0; // Virtual // Liability => 0 is a shortcut for { get { return 0; } }. } public class House : Asset { public decimal Mortgage; public override decimal Liability => Mortgage; // Overridden } public class Stock : Asset { public long SharesOwned; // We won't override Liability here, because the default implementation will do. } }