Hi Everyone,
I would like to know what is the exact purpose of "Virtual" Method in C#
Thanks,
Komathy
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Bikesh SrivastavaPosted Sep 10, 2016, 4:04 PM
Ramesh PalaniappanPosted Sep 10, 2016, 9:28 AM
When an instance method declaration includes a
virtualmodifier, that method is said to be a virtual method. When novirtualmodifier is present, the method is said to be a non-virtual method.The implementation of a non-virtual method is invariant: The implementation is the same whether the method is invoked on an instance of the class in which it is declared or an instance of a derived class. In contrast, the implementation of a virtual method can be superseded by derived classes. The process of superseding the implementation of an inherited virtual method is known as overriding that method.
In a virtual method invocation, the run-time type of the instance for which that invocation takes place determines the actual method implementation to invoke. In a non-virtual method invocation, the compile-time type of the instance is the determining factor. In precise terms, when a method named
Nis invoked with an argument listAon an instance with a compile-time typeCand a run-time typeR(whereRis eitherCor a class derived fromC), the invocation is processed as follows:C,N, andA, to select a specific methodMfrom the set of methods declared in and inherited byC. This is described in.Mis a non-virtual method,Mis invoked.Mis a virtual method, and the most derived implementation ofMwith respect toRis invoked.For every virtual method declared in or inherited by a class, there exists a most derived implementation of the method with respect to that class. The most derived implementation of a virtual method
Mwith respect to a classRis determined as follows:Rcontains the introducingvirtualdeclaration ofM, then this is the most derived implementation ofM.Rcontains anoverrideofM, then this is the most derived implementation ofM.Mwith respect toRis the same as the most derived implementation ofMwith respect to the direct base class ofR.Komathy KMPosted Sep 8, 2016, 7:39 AM
Kindly have a look into the below class hierarchy
If I am trying to access class “A” information from class “D”, I may receive the error message that, “A” created in ambiguous manner, so we are unable to use this style. Because of that reason only we got a “Virtual” keyword. If we put the keyword in class A and trying to call from “D” class the runtime path will generated directly between the class A and D and we can access through that.
Am I Right? Or wrong?
Rajeesh MenothPosted Sep 7, 2016, 5:29 AM
Komathy KMPosted Sep 7, 2016, 5:21 AM
Rajeesh MenothPosted Sep 7, 2016, 5:10 AM
Vinay SinghPosted Sep 7, 2016, 4:37 AM
Midhun TpPosted Sep 7, 2016, 3:14 AM