Abstract class - Can contain abstract members (no body) and concrete members (with implementation). - Can have fields, constructors, and members with any access modifier (private, protected, internal, public). - A class can inherit from only one abstract (or concrete) class. - Represents an "is-a" relationship within a family: Employee as the base for Manager and Developer. - Used to share code and state among related classes. Interface - Defines a contract: methods, properties, events and indexers a type must provide. - Cannot have instance fields or constructors. - Since C# 8, can include default method implementations, static members and private helpers; since C# 11, static abstract members (used for generic math). - A class or struct can implement many interfaces. - Represents a capability: IComparable, IDisposable, IPaymentGateway — usable by unrelated types. Example public interface IPayable { decimal CalculatePay(); } public abstract class Employee : IPayable { protected Employee(string name) => Name = name; public string Name { get; } public abstract decimal CalculatePay(); // each type defines pay public string PaySlip() => $"{Name}: {CalculatePay():C}"; // shared implementation } public sealed class Contractor : IPayable { public decimal CalculatePay() => 50_000m; // not an employee, but payable } Payroll code can depend on IPayable and process both employees and contractors. Choosing between them - Interface: defining dependencies for dependency injection, enabling multiple implementations and test doubles, adding capabilities across unrelated types, public contracts. - Abstract class: sharing implementation and state, controlling construction, template method patterns, or when you want to add new members later with default behaviour for all subclasses. - Often both: an interface for consumers and an abstract base class to help implementers. Versioning note: adding a member to an interface used to break all implementers; default interface methods now allow evolution, while abstract classes can add virtual members safely. Structs can implement interfaces but cannot inherit from abstract classes, which is another reason interfaces are more flexible for contracts.
Ravindra Wadile · · 0 likes