C# Polymorphism

Last modified: July 11, 2021

Polymorphism also known as "many forms", and it occurs when we have many C# classes inherit to each other.

We first create the Shape Base class and create derived class Square. We create a virtual method called the Draw method in the Shape class so that derived classes can inherit it.

In the derived class, we simply override the method.

public class Shape { public virtual void Draw() { Console.WriteLine("Draw a Shape"); } } public class Square: Shape { public override void Draw() { Console.WriteLine("Draw a Square"); } } class Program { static void Main(string[] args) { Shape myShape = new Shape(); myShape.Draw(); //output Draw a Shape Square mySquare = new Square(); mySquare.Draw(); //output Draw a Square } }