Yachit Kumar
What is Virtual Method in C#?
By Yachit Kumar in C# on Nov 04 2012
  • Dinesh Kumar
    Nov, 2012 16

    A virtual method can be redefined. In the C# language, the virtual keyword designates a method that can be overridden in derived classes. This enables you to add new, derived types without modifying the rest of your program. The runtime type of objects thus determines what your program does. Keywords Example NoteThis program introduces two classes, A and B. Class A has a public virtual method called Test. Class B, meanwhile, derives from class A and it provides a public override method called Test as well.The virtual modifier tells the compiler that when any class derived from class A (such as class B) is used, an override method should be used instead of the virtual method. Override MethodProgram that introduces virtual method [C#]using System;class A {public virtual void Test(){Console.WriteLine("A.Test");} }class B : A {public override void Test(){Console.WriteLine("B.Test");} }class Program {static void Main(){// Compile-time type is A.// Runtime type is A as well.A ref1 = new A();ref1.Test();// Compile-time type is A.// Runtime type is B.A ref2 = new B();ref2.Test();} }OutputA.Test B.Test

    • 0
  • Yogesh Sharma
    Nov, 2012 9

    The virtual modifier tells the compiler that when any class derived from class A (such as class B) is used, an override method should be used instead of the virtual method.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS