CSharp - What is Polymorphism

Introduction

A variable of type x can refer to an object that subclasses x.

Suppose we have the following class

class Circle : Shape   // inherits from Shape
{
       public long Radius;
}

class Square : Shape   // inherits from Shape
{
       public decimal Width;
}
class Shape{
       public string Name;
}

Consider the following method:

public static void Display (Shape asset)
{
    System.Console.WriteLine (asset.Name);
}

This method can display both a Circle and a Square, since they are both Shapes:

Circle myCircle = new Circle ... ;
Square mySquare = new Square ... ;
Display (myCircle);
Display (mySquare);

Polymorphism works since subclasses (Circle and Square) have all the features of their base class (Shape).

The converse is not true.

Related Topics