As written in topic - in C# what is the difference between method overloading and polymorphism?
If you know then it would be better if you could give an answer with some examples.
As written in topic - in C# what is the difference between method overloading and polymorphism?
If you know then it would be better if you could give an answer with some examples.
Both method overloading and overriding (in the context of inheritance) are forms of polymorphism. To be more precise:
public class Calculator {
public int Add(int a, int b) {
return a + b;
}
public double Add(double a, double b) {
return a + b;
}
}
public class Animal {
public virtual void MakeSound() {
Console.WriteLine("The animal makes a sound");
}
}
public class Dog : Animal {
public override void MakeSound() {
Console.WriteLine("The dog barks");
}
}
public class Cat : Animal {
public override void MakeSound() {
Console.WriteLine("The cat meows");
}
}
Interface implementation is also a form of polymorphism, as a class implementing an interface must provide an implementation for each of the interface's methods. Here, polymorphism is manifested as the ability to interact with an object based on the more general contract defined by the interface, rather than the specific capabilities of the class.
public interface IMovable {
void Move();
}
public class Car : IMovable {
public void Move() {
Console.WriteLine("The car drives");
}
}
public class Boat : IMovable {
public void Move() {
Console.WriteLine("The boat sails");
}
}
In all these forms, polymorphism provides a way to handle different types of objects (distinguished by classes or method signatures) in a uniform manner.