Polymorphism in C# refers to the ability of objects to take on different forms. It allows methods to behave differently based on the object that calls them, enabling flexibility and reusability in code.
Key Concepts of Polymorphism
Compile-Time Polymorphism (Static Polymorphism)
Achieved through method overloading and operator overloading.
The behavior is determined at compile time.
Run-Time Polymorphism (Dynamic Polymorphism)
Achieved through method overriding using inheritance.
The behavior is determined at runtime.
1. Compile-Time Polymorphism (Method Overloading)
Definition:
Method overloading allows multiple methods with the same name but different parameters in the same class.
class Animal {
public virtual void Speak() {
Console.WriteLine("The animal makes a sound.");
}
}
class Dog : Animal {
public override void Speak() {
Console.WriteLine("The dog barks.");
}
}
class Cat : Animal {
public override void Speak() {
Console.WriteLine("The cat meows.");
}
}
// Usage
Animal animal1 = new Dog();
animal1.Speak(); // Output: The dog barks.
Animal animal2 = new Cat();
animal2.Speak(); // Output: The cat meows.
interface IShape {
void Draw();
}
class Circle : IShape {
public void Draw() {
Console.WriteLine("Drawing a circle.");
}
}
class Rectangle : IShape {
public void Draw() {
Console.WriteLine("Drawing a rectangle.");
}
}
// Usage
IShape shape1 = new Circle();
shape1.Draw(); // Output: Drawing a circle.
IShape shape2 = new Rectangle();
shape2.Draw(); // Output: Drawing a rectangle.
class BaseClass {
public virtual void Display(string message) {
Console.WriteLine("Base class message: " + message);
}
}
class DerivedClass : BaseClass {
public override void Display(string message) {
Console.WriteLine("Derived class message: " + message);
}
// Overloading
public void Display(string message, int count) {
for (int i = 0; i < count; i++) {
Console.WriteLine(message);
}
}
}
// Usage
BaseClass baseObj = new BaseClass();
baseObj.Display("Hello from Base!"); // Output: Base class message: Hello from Base!
DerivedClass derivedObj = new DerivedClass();
derivedObj.Display("Hello from Derived!"); // Output: Derived class message: Hello from Derived!
derivedObj.Display("Hello again!", 3); // Output: Hello again! (3 times)