Polymorphism is one of the four fundamental principles of Object-Oriented Programming (OOP) in C#. It allows objects to be treated as instances of their parent class, enabling a single interface to represent different underlying forms (data types). This is particularly useful in method overriding and interface implementation.
In C#, polymorphism can be achieved through two primary means: method overriding and interfaces. When a derived class provides a specific implementation for a method that is already defined in its base class, polymorphism allows that derived class to be used interchangeably with the base class.
Here's an example to illustrate polymorphism using method overriding:
public class Animal
{
public virtual void Speak()
{
Console.WriteLine("An animal makes a sound");
}
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof!");
}
}
public class Cat : Animal
{
public override void Speak()
{
Console.WriteLine("Meow!");
}
}
public class Program
{
public static void Main(string[] args)
{
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.Speak(); // Output: Woof!
myCat.Speak(); // Output: Meow!
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?