Both involve methods with the same name, but they are different concepts. Method overloading - Same method name, different parameter lists (number, type or order of parameters). - Can be in the same class. - Resolved at compile time by the compiler, based on argument types: compile-time (static) polymorphism. - Return type alone cannot distinguish overloads. - No special keywords needed. public class Calculator { public int Add(int a, int b) => a + b; public double Add(double a, double b) => a + b; public int Add(int a, int b, int c) => a + b + c; } Method overriding - Same method signature in a derived class, replacing a virtual or abstract base method. - Requires inheritance (base class and derived class). - Resolved at runtime based on the actual object type: runtime (dynamic) polymorphism. - Uses virtual (or abstract) in the base class and override in the derived class. public class Notification { public virtual string Send() => "Sending generic notification"; } public class SmsNotification : Notification { public override string Send() => "Sending SMS"; } Notification n = new SmsNotification(); Console.WriteLine(n.Send()); // "Sending SMS" — decided at runtime Side-by-side - Purpose: overloading offers multiple ways to call the same operation; overriding changes behaviour in subclasses. - Signature: different (overloading) vs identical (overriding). - Binding: compile time vs runtime. - Inheritance: not required vs required. - Keywords: none vs virtual/abstract plus override. - Static methods: can be overloaded but cannot be overridden. Quick real-world mention: Console.WriteLine is heavily overloaded; ToString(), Equals() and GetHashCode() are commonly overridden from System.Object. Related trap: using new in a derived class hides a method rather than overriding it, so calls through a base reference still run the base version.
Ravindra Wadile · · 0 likes