Team LiB
Previous Section Next Section

Overriding

Three keywords are related to overriding methods: override, base, and new. These allow you to use polymorphism, access an overridden method, and indicate a method override.

override

The override keyword is used to invoke polymorphism. It allows a derived class to provide a method with the same name and parameters. The derived class may enhance or modify a method that is inherited through a base class.

base

The base keyword is used to access the base method that has been overridden. Remember that C# supports only single inheritance. If you have class C derived from class B, which is derived from class A, and each class has a virtual or overridable version of the same method, you can call only the method that is in the base class, not in the base class of the base class.

new

The new keyword, in addition to being used to allocate memory, can also be used to hide data members, methods, and type members of a base class. The new keyword is implied and is used to signal that a method has been replaced in the derived class. This keyword is not required, but it is recommended for code readability. Any derived class that implements a method with the same signature will be treated as if it had been marked as new.

The following example demonstrates overriding.

Code Example: Overriding
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
                  A MyA = new D();
                  B MyB = new C();

                 MyA.Display();       //Calls D Display
                 MyB.Display();       //Calls C Display
                 //Followed by B's Display via the base keyword
            }
      }
      class A
      {
            public virtual void Display()
            {
                  Console.WriteLine("Class A's Display Method");
            }
      }
      class B : A
      {
            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");
                  base.Display();
            }
      }
      class D : C
      {
            public override void Display()
            {
                  Console.WriteLine("Class D's Display Method");
            }
      }
}
End example

Team LiB
Previous Section Next Section