Overloading vs Overriding
Overloading vs Overriding
Difference Between Overloading and Overriding in C#
1. Method Overloading
- Same method name, different parameters.
- Occurs within the same class.
- Compile-time (static) polymorphism.
- Parameters must change (type, number, or order).
C# Example:
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; }
}
2. Method Overriding
- Same method name, same parameters.
- Occurs in different classes using inheritance.
- Runtime (dynamic) polymorphism.
- Uses
virtual and override keywords.
C# Example:
class Car
{
public virtual void Drive()
{
Console.WriteLine("Car is driving");
}
}
class SportsCar : Car
{
public override void Drive()
{
Console.WriteLine("SportsCar is driving fast!");
}
}
No comments:
Post a Comment