Polymorphism means "many forms": the same operation can behave differently depending on the type of object it works on. It lets code depend on general abstractions while specific types supply their own behaviour. 1. Compile-time (static) polymorphism Decided by the compiler. - Method overloading: same name, different parameters. public decimal Area(decimal side) => side * side; public decimal Area(decimal width, decimal height) => width * height; - Operator overloading: public static Money operator +(Money a, Money b) => ... - Generics: one method or class working with many types (List<T>, Max<T>). 2. Runtime (dynamic) polymorphism Decided at runtime by the actual object type. - Overriding virtual or abstract methods: public abstract class Notification { public abstract Task SendAsync(string to, string text); } public class EmailNotification : Notification { public override Task SendAsync(string to, string text) => /* SMTP */ Task.CompletedTask; } public class SmsNotification : Notification { public override Task SendAsync(string to, string text) => /* SMS API */ Task.CompletedTask; } foreach (Notification n in channels) await n.SendAsync(user, "Your order has shipped"); // each type sends its own way - Interface implementation: IPaymentGateway gateway = useRazorpay ? new RazorpayGateway() : new StripeGateway(); await gateway.ChargeAsync(amount); Why it matters in real projects - Open/Closed principle: add a new notification channel by adding a class, without changing the loop that sends notifications. - Dependency injection and testing: code depends on interfaces, and tests substitute fakes. - Removes long if/else or switch chains based on type. Related details - Upcasting (derived to base reference) is implicit; downcasting requires a cast or pattern matching (if (n is SmsNotification sms)). - Method hiding with new does not provide runtime polymorphism. - Pattern matching with switch expressions provides another form of type-based behaviour, useful for closed sets of types such as records. A good interview answer defines polymorphism, gives one compile-time and one runtime example, and explains a project scenario where it removed conditional logic.
Ravindra Wadile · · 0 likes