CAB201

icon picker
CAB Polymorphism

C# Polymorphism: A Quick Guide

Polymorphism in C# allows objects to be treated as instances of their parent class. It enables you to perform a single action in different ways. There are two main types: method overriding and method overloading.

1. Method Overriding

Method overriding allows a derived class to provide a specific implementation of a method that is already defined in its base class.
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound");
}
}

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

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

// Usage
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();

myAnimal.MakeSound(); // Output: The animal makes a sound
myDog.MakeSound(); // Output: The dog barks
myCat.MakeSound(); // Output: The cat meows
Key Points:
Use virtual keyword in the base class method
Use override keyword in the derived class method

2. Method Overloading

Method overloading allows multiple methods in the same class with the same name but different parameters.
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}

public double Add(double a, double b)
{
return a + b;
}

public int Add(int a, int b, int c)
{
return a + b + c;
}
}

// Usage
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(5, 10)); // Output: 15
Console.WriteLine(calc.Add(5.5, 10.5)); // Output: 16
Console.WriteLine(calc.Add(5, 10, 15)); // Output: 30
Key Points:
Methods must have the same name but different parameter lists
Return type alone is not enough to distinguish overloaded methods

Benefits of Polymorphism

Increases code reusability
Reduces complexity
Improves code flexibility and maintainability
Remember, polymorphism is a powerful feature in object-oriented programming. It allows you to write more flexible and scalable code by treating related objects in a uniform way.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.