Polymorphism means "many forms". In C#, it allows methods to have different implementations depending on the object that is calling them. This is one of the core concepts of Object-Oriented Programming (OOP).
Print()
function is called — but the way it prints differs depending on the document type.
You can define multiple methods 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;
}
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(3, 4)); // Output: 7
Console.WriteLine(calc.Add(3.2, 4.8)); // Output: 8
}
}
With inheritance, a derived class can override a base class method using the override
keyword.
class Animal
{
public virtual void Sound()
{
Console.WriteLine("Animal makes a sound");
}
}
class Dog : Animal
{
public override void Sound()
{
Console.WriteLine("Dog barks");
}
}
class Cat : Animal
{
public override void Sound()
{
Console.WriteLine("Cat meows");
}
}
class Program
{
static void Main()
{
Animal myAnimal;
myAnimal = new Dog();
myAnimal.Sound(); // Output: Dog barks
myAnimal = new Cat();
myAnimal.Sound(); // Output: Cat meows
}
}
Feature | Overloading | Overriding |
---|---|---|
Occurs | Compile time | Run time |
Inheritance | Not required | Required |
Keyword used | None | virtual / override |
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!