wasAsked.

Difference between Method Overriding and Method Hiding?

Impetus · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

Both let a derived class define a member with the same signature as a base member, but they behave very differently at runtime. Method overriding (virtual / override) - The base method is marked virtual (or abstract); the derived method uses override. - Uses dynamic (runtime) dispatch: the method chosen depends on the actual object type, not the reference type. - This is runtime polymorphism. Method hiding (new) - The derived class declares a method with the same signature using the new keyword (the base method need not be virtual). - Uses static (compile-time) binding: the method chosen depends on the reference type. - The base method is not replaced, only hidden when accessed through the derived type. Example: public class Payment { public virtual string Process() => "Generic payment"; public string Receipt() => "Generic receipt"; } public class CardPayment : Payment { public override string Process() => "Card payment"; // overriding public new string Receipt() => "Card receipt"; // hiding } Payment p = new CardPayment(); p.Process(); // "Card payment" -> override honoured through base reference p.Receipt(); // "Generic receipt" -> hidden method ignored through base reference CardPayment c = new CardPayment(); c.Receipt(); // "Card receipt" Comparison - Keyword: override vs new. - Base requirement: virtual/abstract/override vs none. - Binding: runtime vs compile time. - Polymorphism: yes vs no. - Calling base: both can call base.Method(). - Without the new keyword, hiding still happens but the compiler shows warning CS0108. When to use - Overriding: whenever subclasses should customise behaviour polymorphically (most designs). - Hiding: rarely — mainly when a base class you do not control adds a member that clashes with yours, or for special cases like returning a more specific type from a property (covariant return types in C# 9 now cover many of those cases with override). Hiding often leads to surprising bugs because behaviour changes depending on the variable's declared type, so prefer overriding.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics