When a method declaration in a class is preceded by a virtual modifier, we call it a virtual method, whereas the other is non-virtual. No more static,abstract, or override modifiers, are allowed after using the virtual modifier.
For a non-virtual method, the method is executed regardless of whether it is invoked by an instance of its class or by an instance of the derived class of the class. For a virtual method, its execution can be changed by the derived class, which is implemented by the overload of the method.
The following example illustrates the difference between a virtual method and a Non-virtual method.
Program Listing 14-3:
Using System;
Class A
{public
void F () {Console.WriteLine ("A.F");}
public virtual void G () {Console.WriteLine ("A.G");
}
Class b:a
{
new public void F () {Console.WriteLine ("B.f");}
public override void G () {Console.WriteLine ("B.G");}
Class Tese
{
static void Main () {
B b=new b ();
A a=b;
A.F ();
B.f ();
A.G ();
B.G ();
}
In the example, Class A provides two methods: Non-virtual F and Virtual method G. Class B provides a new Non-virtual method F, which overrides the inherited F; Class B also overloads the inherited method G. Then the output should be:
A.f
B.f
B.g
B.g
Notice in this example that method A. G () actually calls the B.G, not the A.G. This is because the compile value is a, but the Run-time value is B, so B completes the actual call to the method.