wasAsked.

Types of Polymorphism

HCA Healthcare · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

C# commonly demonstrates compile-time polymorphism through overload resolution and run-time polymorphism through virtual dispatch or interface dispatch. Parametric polymorphism through generics is also important because one algorithm works safely with many types. ```csharp public sealed class PriceFormatter { public string Format(decimal value) => value.ToString("0.00"); public string Format(decimal value, string currency) => $"{currency} {value:0.00}"; // compile-time overload selection } public interface IDiscount { decimal Apply(decimal subtotal); } public sealed class PercentageDiscount(decimal rate) : IDiscount { public decimal Apply(decimal subtotal) => subtotal * (1 - rate); } static T Last<T>(IReadOnlyList<T> values) => values[^1]; // generic ``` When `IDiscount.Apply` is called, the runtime selects the concrete implementation. Overloading selects the best compatible signature at compile time. Method hiding with `new` is not overriding: selection depends on the reference's compile-time type, so it is usually less suitable for substitutable behavior.

Prince Yadav · · 0 likes

Polymorphism in C# comes in two main categories, with a few forms in each. 1. Compile-time polymorphism (static binding) The compiler decides which code to call. a) Method overloading public void Log(string message) { } public void Log(string message, Exception ex) { } public void Log(Exception ex) { } b) Operator overloading public readonly record struct Money(decimal Amount, string Currency) { public static Money operator +(Money a, Money b) => a.Currency == b.Currency ? new(a.Amount + b.Amount, a.Currency) : throw new InvalidOperationException("Currency mismatch"); } c) Generics (parametric polymorphism) public static T Clamp<T>(T value, T min, T max) where T : IComparable<T> => value.CompareTo(min) < 0 ? min : value.CompareTo(max) > 0 ? max : value; 2. Runtime polymorphism (dynamic binding) The method executed depends on the actual object type at runtime. a) Method overriding with virtual/abstract and override public abstract class Discount { public abstract decimal Apply(decimal price); } public class Percentage(decimal pct) : Discount { public override decimal Apply(decimal p) => p - p * pct / 100; } public class Flat(decimal amount) : Discount { public override decimal Apply(decimal p) => Math.Max(0, p - amount); } Discount d = isFestival ? new Percentage(20) : new Flat(100); decimal final = d.Apply(1500); b) Interface-based polymorphism public interface IExporter { byte[] Export(Report r); } IExporter exporter = format switch { "pdf" => new PdfExporter(), "xlsx" => new ExcelExporter(), _ => new CsvExporter() }; Other mechanisms worth mentioning - Delegates and lambdas: pluggable behaviour without inheritance (Func<decimal, decimal> discount). - dynamic: late binding resolved at runtime by the DLR. - Pattern matching: type-based behaviour with switch expressions. - Method hiding (new) is not polymorphism, because calls bind to the reference type. Comparison - Binding time: compile time vs runtime. - Mechanism: overloading, operators, generics vs overriding and interfaces. - Performance: compile-time is slightly faster (no virtual dispatch), but the difference is negligible in most applications. - Flexibility: runtime polymorphism allows choosing implementations through configuration or dependency injection.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics