(C# Language) Polymorphism in C#

This tutorial is for explaining a few programs that exhibit the idea of polymorphism. I won't be able to go into the philosophy of polymorphism. The whole point of this tutorial is to introduce you to the syntax, and about how the usual things are done in a C# syntax.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

Recall of Polymorphism

All types - classes, records, structs - are polymorphic because the ultimate base class of all the types is the Object class.

In the dotnet framework each class directly or indirectly inherits from the Object base class. This class provides a ToString method that can be overridden in the derived classes to return a text that describes the derived class. We shall examine polymorphism by overriding this method.

Consider a class called A that overrides the ToString function of the base class.

class A : Object
{
  public override string ToString()
  {
    return "A - to String!";
  }
}

Consider also a class B that does the same thing.


class B : Object
{
  public override string ToString()
  {
    return "B - to String!";
  }
}

Let's also add a class C that does the same thing.


class C : Object
{
  public override string ToString()
  {
    return "C - to String!";
  }
}

Inside the main function we create a polymorphic array of Object[] containing instances of A, B and C. Notice that the data-type of the array is Object, whereas the array contains instances of classes derived from the Object class.


class Program
{
  static void Main()
  {
    Object[] objects = { new A(), new B(), new C() };

    foreach (Object o in objects)
    {
      Console.WriteLine(o.ToString());
    }

    // prints 
    // A - to String! 
    // B - to String! 
    // C - to String! 
  }
}  
  
  

A foreach loop runs on the Object array and calls the over-ridden ToString method.

Runtime binding ensures that the correct function is called.

Run the project to verify that the respective strings are printed.

This is how polymorphism works in C# also.

Video Explanation (see it happen!)

Please watch the following youtube video:

Preventing override of Base class Methods

A derived class can prevent further over-riding of the virtual methods. For this the sealed keyword is used. Let's take an example.


class CBase
{
  public virtual void fx() 
  { 
  }
}

Consider a base class that has marked a function as virtual. Since the function has been marked virtual, it can be over-ridden in its derived class. The derived class has over-ridden the function but marked it as sealed. This means that it has prevented it from being over-ridden in further derived classes.


class CDerived : CBase
{
  public sealed override void fx()
  {
  }
}

We get a compiler error if we attempt to over-ride this function in a deeper derived class as you see here.


class CDerived2 : CDerived
{
  // COMPILER ERROR HERE 
  public override void fx()
  {
  }
}

Hiding base class members

A derived class can hide a base class member by using the new keyword to provide a member of the same name. Let us take an example.

Consider a base class that has a method called, say, MyMethod. This method prints some text to the console.


class CBase
{

  public void MyMethod() => Console.WriteLine("CBase.MyMethod");

}

Next let's inherit a derived class. This class also has a method of the same name. This method is marked with the new keyword to hide the base class method.


class CDerived : CBase
{

  public new void MyMethod() => Console.WriteLine("CDerived.MyMethod");

}

Inside main we create an object of the derived class.

When the MyMethod is called on this object, the derived class function executes as expected. The base class code is hidden.


class Program
{
  static void Main()
  {
    CDerived cd = new CDerived();

    // prints CDerived.MyMethod 
    cd.MyMethod();

    // prints CBase.MyMethod 
    (cd as CBase).MyMethod();
  }
}

We can still call the base class version if we cast this object to its base class. We have used the as keyword to cast CDerived to CBase.


This Blog Post/Article "(C# Language) Polymorphism in C#" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.