wasAsked.

How do you implement overriding

HCA Healthcare · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

Overriding lets a derived class provide its own implementation of a method defined in a base class, and the correct version is chosen at runtime based on the actual object type. Steps 1. Mark the base method virtual (or abstract in an abstract class). 2. In the derived class, declare a method with the same signature using override. 3. Optionally call the base implementation with base.MethodName(). public class Employee { public string Name { get; init; } = ""; public decimal BaseSalary { get; init; } public virtual decimal CalculatePay() => BaseSalary; public override string ToString() => $"{Name}: {CalculatePay():C}"; // overriding object.ToString } public class Manager : Employee { public decimal Bonus { get; init; } public override decimal CalculatePay() => base.CalculatePay() + Bonus; } public class Contractor : Employee { public int Hours { get; init; } public decimal HourlyRate { get; init; } public sealed override decimal CalculatePay() => Hours * HourlyRate; // sealed: no further overriding } List<Employee> staff = [ new Employee { Name = "Asha", BaseSalary = 50000 }, new Manager { Name = "Ravi", BaseSalary = 80000, Bonus = 15000 }, new Contractor { Name = "Neha", Hours = 120, HourlyRate = 900 } ]; foreach (var e in staff) Console.WriteLine(e); // each uses its own CalculatePay Rules - Same name, parameters and return type (C# 9 allows covariant return types for overrides). - Same access modifier as the base method. - Static, non-virtual and private methods cannot be overridden. - Properties, indexers and events can be virtual and overridden too. - sealed override prevents further overriding in subclasses. - Abstract methods must be overridden by non-abstract derived classes. Overriding vs hiding: if you omit virtual/override and use new, the method is only hidden and calls through a base reference still use the base method. Design advice: use virtual methods deliberately (they are extension points), follow the Liskov Substitution Principle so overrides do not break expected behaviour, and consider composition or interfaces when inheritance hierarchies grow deep.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics