Team LiB
Previous Section Next Section

Virtual Methods

Polymorphism is the idea that you can call a particular method based on the class that was used to create the instance of the object. In C#, you must use the override and virtual keywords explicitly to gain this functionality.

A virtual method is a method in a base class that can be ignored in favor of a derived class's version of the same method.

Caution 

It is quite easy to confuse the concept of overriding with that of overloading. The big difference between these two concepts is the basis of polymorphism. A virtual method can be overridden by a method of a derived class that has the exact same prototype or method signature. Overloading a method is when the method has the same name but not the same arguments in the same order.

Pure virtual methods are used in abstract classes, and they do not have a method definition. They exist solely as a placeholder for a derived class to implement that inherits from the abstract class.

The following example demonstrates the use of virtual methods.

Code Example: Virtual Methods
Start example
using System;

namespace Client.Chapter_5___Building_Your_Own_Classes
{
      class MyMainClass
      {
            static void Main(string[] args)
            {
             //The function called is based on the type called by new.
              //The variable MyB is actually a C object, and when you call a method
              //marked as override, it calls that object's method rather than the
                  //method inherited.
                   B MyB = new C();

                  MyB.Display();       //Calls C's Display
            }
      }

      //Marks a class as abstract or a method as abstract, which means a class instance
      //cannot be made. In this instance, virtual is implied.
      abstract class A
      {
            public abstract void Display();
      }
      class B : A
      {
            //Marks a method as overriding a method that was inherited.
            public override void Display()
            {
                  Console.WriteLine("Class B's Display Method");
            }
      }
      class C : B
      {
            public override void Display()
            {
                  Console.WriteLine("Class C's Display Method");
            }
      }
      class D : C
      {
            public override void Display()
            {
                  Console.WriteLine("Class D's Display Method");
            }
      }
}
End example

Team LiB
Previous Section Next Section