Both define contracts, but they solve different problems. Interface - Describes a capability: what a type can do (IComparable, IDisposable, IPaymentGateway). - A class can implement many interfaces. - No instance fields or constructors. Since C# 8 interfaces can have default method implementations and static members (C# 11 added static abstract members), but they still cannot hold instance state. - Works across unrelated types: a Car and a Drone can both be IMovable. - Struct types can implement interfaces. Abstract class - Describes an "is-a" relationship and a shared base: Shape for Circle and Rectangle. - A class can inherit from only one class. - Can have constructors, fields, protected members, and a mix of implemented and abstract methods. - Good for sharing code and enforcing a skeleton (template method pattern). When I choose an interface - Defining dependencies for dependency injection and testing (IOrderRepository, IEmailSender). - When unrelated classes need the same capability. - When I want maximum flexibility and multiple implementations, possibly from other teams or libraries. - For public library contracts, though I am careful because adding members later can break implementers (default interface methods help). When I choose an abstract class - Several closely related classes share real implementation and state, such as common validation, logging or a fixed algorithm with customisable steps. - I want to provide protected helpers or enforce constructor requirements. - I need to add new behaviour later without breaking derived classes (add a virtual method with a default implementation). Combined approach (common in practice) Define an interface for consumers and provide an abstract base class as an optional helper: public interface INotificationSender { Task SendAsync(Notification n); } public abstract class NotificationSenderBase : INotificationSender { public async Task SendAsync(Notification n) { Validate(n); await SendCoreAsync(n); } protected abstract Task SendCoreAsync(Notification n); private static void Validate(Notification n) { /* shared rules */ } } Rule of thumb: default to interfaces for contracts and dependencies; use abstract classes when there is meaningful shared code within a family of related types.
Ravindra Wadile · · 0 likes