Working with C# Polymorphism: An example with explanation

Polymorphism is the ability of an object to take on multiple forms. In C#, polymorphism is achieved through inheritance. Polymorphism allows you to write code that can work with objects of different classes that have a common base class. For example, you can have a method that takes an object of the base class as a parameter, and then you can pass objects of any derived class to that method.

Here's a program based on C# polymorphism with an explanation:
 
using System;

namespace PolymorphismExample
{
    public class Animal
    {
        public virtual void MakeSound()
        {
            Console.WriteLine("The animal makes a sound");
        }
    }

    public class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("The dog barks");
        }
    }

    public class Cat : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("The cat meows");
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            Animal animal = new Animal();
            animal.MakeSound();

            Dog dog = new Dog();
            dog.MakeSound();

            Cat cat = new Cat();
            cat.MakeSound();

            Animal animalDog = new Dog();
            animalDog.MakeSound();

            Animal animalCat = new Cat();
            animalCat.MakeSound();

            Console.ReadKey();
        }
    }
}
In this program, we have a base class called Animal with a virtual method called MakeSound(). We then have two derived classes, Dog and Cat, which both inherit from Animal and override the MakeSound() method with their own implementation.

In the Program class, we create instances of Animal, Dog, and Cat, and call their MakeSound() methods. We then create instances of Animal that are actually Dog and Cat objects, respectively, and call their MakeSound() methods.

The output of the program is as follows:
The animal makes a sound
The dog barks
The cat meows
The dog barks
The cat meows
This demonstrates polymorphism in action - the MakeSound() method is called on objects of different types (Animal, Dog, Cat) and produces different behavior based on the actual type of the object being used at runtime.