← Back

Interfaces vs Abstract Classes

2026-01-06 22:20 Β· πŸ‘ 27401

#c#

πŸš€ C# Tip β€” Interfaces vs Abstract Classes (When to Use Each)

Choosing between an interface and an abstract class is not a syntax decision. It’s an architecture decision.

Both exist to model contracts, but they solve different problems.


🧠 The Core Difference

  • Interface β†’ What a class can do
  • Abstract class β†’ What a class is

That distinction alone solves most debates.


🧩 Interfaces β€” Contracts & Capabilities

public interface IPaymentGateway
{
    Task ChargeAsync(decimal amount);
}

βœ… When interfaces shine

  • Multiple inheritance of behavior
  • Dependency Injection
  • Plugin/extensibility models
  • Clean Architecture boundaries
  • Unit testing & mocking

πŸ‘ Strengths

  • A class can implement many interfaces
  • No implementation inheritance
  • Clear separation of concerns
  • Ideal for cross-cutting capabilities

🧱 Abstract Classes β€” Shared Identity & Base Behavior

public abstract class PaymentGateway
{
    protected void Log(string message) { }

    public abstract Task ChargeAsync(decimal amount);
}

βœ… When abstract classes shine

  • Shared implementation is required
  • Protected helpers are needed
  • Strong β€œis-a” relationship
  • Template Method pattern

πŸ‘ Strengths

  • Can hold state
  • Can provide base behavior
  • Can evolve without breaking all implementers

⚠️ Key Trade-Offs (That Matter in Practice)

❌ Interfaces

  • No shared state
  • Breaking changes hurt more
  • Can lead to β€œinterface explosion” if abused

❌ Abstract Classes

  • Single inheritance only
  • Tighter coupling
  • Harder to refactor later
  • Less flexible in large systems

🧠 Modern C# Changes (Important!)

Default interface methods (C# 8+)

public interface ILogger
{
    void Log(string msg);

    void Info(string msg) => Log($"INFO: {msg}");
}

βœ”οΈ Helps evolve interfaces
❌ Does not replace abstract classes
❌ No state, no fields


βš–οΈ Comparison at a Glance

Aspect Interface Abstract Class
Multiple inheritance βœ… ❌
Holds state ❌ βœ…
DI-friendly βœ… ⚠️
Shared code ⚠️ (default methods) βœ…
Coupling Low Higher
Best for Capabilities Base identity

πŸ—οΈ Real-World Rule of Thumb

  • Public API / boundaries β†’ Interface
  • Domain base type β†’ Abstract class
  • DI & test seams β†’ Interface
  • Shared internal behavior β†’ Abstract class

Start with an interface.
Move to an abstract class only when sharing behavior becomes unavoidable.


🎯 Final Takeaway

Interfaces give you flexibility.
Abstract classes give you reuse.

Choose based on coupling vs freedom, not convenience.

Bad abstractions are worse than no abstractions.


#csharp #dotnet #oop #architecture #cleancode #softwareengineering

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please reload the page.