Example of method overloading in C#:
public class Calculator
{
// Overloaded method for adding two integers
public int Add(int a, int b)
{
return a + b;
}
// Overloaded method for adding three integers
public int Add(int a, int b, int c)
{
return a + b + c;
}
// Overloaded method for adding two doubles
public double Add(double a, double b)
{
return a + b;
}
}
In this example, the Calculator
class has three methods named Add
, but each method has a different set of parameters. The compiler resolves the method call based on the number and types of arguments passed during the method call.
Example of method overriding in C#:
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks");
}
}
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Cat meows");
}
}
In this example, the Animal
class has a virtual method MakeSound()
, and the Dog
and Cat
classes override this method with their specific implementations. When you call the MakeSound()
method on an instance of Dog
or Cat
, the appropriate overridden version of the method is executed based on the actual object's type.
To summarize, method overloading is about having multiple methods with the same name but different signatures in the same class, and the decision of which method to call is made by the compiler during compile-time. Method overriding is about providing a specific implementation for a method in a subclass that is already defined in its superclass, and the decision of which method to call is made at runtime based on the actual object's type.