What is Virtual Method

What is Virtual Method C#

In object-oriented programming, a virtual function or virtual method can be changed by an overriding member in a derived class by a method with the same signature. In order to create virtual function, precede the method's declaration in the base class with the "virtual" modifier.

Output :

Calling Base Class !!

Calling Derived Class !!

What is Virtual functions C#

When calling a virtual method, the run-time type of the instance for which that invocation takes place determines the actual method implementation to invoke. From the above example, when we call first time Display(), compile time type is "baseClass" and runtime type also is "baseClass". When second time call Display(), compile time type is "baseClass" and runtime type is "derivedClass".

From the above example we can understand that with "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object. More about.... Early Binding and Late binding
Interview questions and answers C#

Virtual methods are similar to abstract methods in base classes except their implementation on derived classes is optional. More about.... Abstract Classes

Note: By default, methods are non-virtual. You cannot override a non-virtual method.
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About