Net-informations.com
SiteMap  | About    

What is Virtual Method

What is Virtual Method C# vb.net asp.net

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.

class baseClass { public virtual void Display() { Console.WriteLine("Calling Base Class !!"); } } class derivedClass : baseClass { public override void Display() { Console.WriteLine("Calling Derived Class !!"); } } class Program { static void Main() { baseClass baseObj = new baseClass(); baseObj.Display(); baseClass deriveObj = new derivedClass(); deriveObj.Display(); } }

Output :

Calling Base Class !!

Calling Derived Class !!

What is Virtual functions C# vb.net asp.net

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# vb.net asp.net

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.







net-informations.com (C) 2016    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.