0
0
C Sharp (C#)programming~5 mins

Why polymorphism matters in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Polymorphism lets us use one name for different actions. It helps make code simpler and easier to change.

When you want different objects to respond differently to the same command.
When you want to add new features without changing old code.
When you want to write code that works with many types of objects.
When you want to organize code so it is easier to understand and maintain.
Syntax
C Sharp (C#)
public class Animal {
    public virtual void Speak() {
        Console.WriteLine("Animal sound");
    }
}

public class Dog : Animal {
    public override void Speak() {
        Console.WriteLine("Bark");
    }
}

public class Cat : Animal {
    public override void Speak() {
        Console.WriteLine("Meow");
    }
}

virtual means the method can be changed in child classes.

override means the child class changes the parent's method.

Examples
Even though the type is Animal, the Dog's Speak method runs.
C Sharp (C#)
Animal myAnimal = new Dog();
myAnimal.Speak();  // Output: Bark
The Cat's Speak method runs because of polymorphism.
C Sharp (C#)
Animal myAnimal = new Cat();
myAnimal.Speak();  // Output: Meow
We can treat different animals the same way and call Speak on each.
C Sharp (C#)
List<Animal> animals = new List<Animal> { new Dog(), new Cat() };
foreach (var animal in animals) {
    animal.Speak();
}
Sample Program

This program shows how different animals speak differently using the same method name.

C Sharp (C#)
using System;
using System.Collections.Generic;

public class Animal {
    public virtual void Speak() {
        Console.WriteLine("Animal sound");
    }
}

public class Dog : Animal {
    public override void Speak() {
        Console.WriteLine("Bark");
    }
}

public class Cat : Animal {
    public override void Speak() {
        Console.WriteLine("Meow");
    }
}

public class Program {
    public static void Main() {
        List<Animal> animals = new List<Animal> { new Dog(), new Cat(), new Animal() };
        foreach (var animal in animals) {
            animal.Speak();
        }
    }
}
OutputSuccess
Important Notes

Polymorphism helps keep code flexible and easy to extend.

It works best with inheritance and method overriding.

Without polymorphism, you would need many if-else checks for types.

Summary

Polymorphism lets one method name work for different types.

It makes code easier to write, read, and change.

It is a key idea in object-oriented programming.