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

Why polymorphism matters in C Sharp (C#) - See It in Action

Choose your learning style9 modes available
Why polymorphism matters
📖 Scenario: Imagine you are building a simple program to manage different types of animals in a zoo. Each animal can make a sound, but the sound is different for each animal. You want to write code that can handle any animal without knowing exactly which type it is.
🎯 Goal: Build a small C# program that shows how polymorphism lets you treat different animal types the same way while they behave differently.
📋 What You'll Learn
Create a base class called Animal with a method MakeSound().
Create two classes Dog and Cat that inherit from Animal and override MakeSound().
Create a list of Animal objects containing both Dog and Cat instances.
Use a loop to call MakeSound() on each animal and print the result.
💡 Why This Matters
🌍 Real World
Polymorphism is used in many programs where different objects share common behavior but implement it differently, like different types of animals, vehicles, or user interface elements.
💼 Career
Understanding polymorphism is essential for software developers to write clean, reusable, and extendable code, which is a key skill in professional programming jobs.
Progress0 / 4 steps
1
Create the base class Animal
Create a public class called Animal with a public virtual method MakeSound() that returns a string "Some sound".
C Sharp (C#)
Need a hint?

Use public virtual string MakeSound() inside the Animal class.

2
Create Dog and Cat classes inheriting Animal
Create two public classes called Dog and Cat that inherit from Animal. Override the MakeSound() method in Dog to return "Bark" and in Cat to return "Meow".
C Sharp (C#)
Need a hint?

Use public override string MakeSound() in both Dog and Cat classes.

3
Create a list of animals
Create a List<Animal> called animals and add one Dog and one Cat object to it.
C Sharp (C#)
Need a hint?

Use List<Animal> and add new Dog() and new Cat() to it.

4
Call MakeSound() on each animal and print
Use a foreach loop with variable animal to go through animals and print the result of animal.MakeSound().
C Sharp (C#)
Need a hint?

Use foreach (Animal animal in animals) and inside the loop Console.WriteLine(animal.MakeSound()).