MediumConcept

What is the difference between an abstract class and an interface in C#?

Technology:
C#
Experience:
Junior,
Mid-level

Quick answer

An abstract class can hold state, constructors and partial implementation but a class can inherit only one, while an interface defines a contract that a class can implement many of.

Detailed explanation

Use an abstract class when related classes share fields, constructor logic or common behaviour, and you want to force subclasses to fill in the rest. A class can extend only one base class, so this is a strong coupling.

Use an interface to describe a capability (IDisposable, IComparable, IEmailSender) that unrelated types can implement, and to make code testable and replaceable through dependency injection. Since C# 8 interfaces may include default method implementations, but they still cannot hold instance fields. A common guideline: start with an interface for the contract, and add an abstract base class only if there is real shared code.

Example

csharp
public interface INotifier { void Send(string message); }

public abstract class NotifierBase : INotifier
{
    protected readonly ILogger Logger;
    protected NotifierBase(ILogger logger) => Logger = logger;
    public abstract void Send(string message);
}

Key points

  • Abstract class: shared state and code, single inheritance
  • Interface: contract, multiple implementation
  • Interfaces make dependency injection and testing easier
  • C#Easy

    What is the difference between string and StringBuilder in C#?

    A string is immutable, so every change creates a new string object, while StringBuilder is a mutable buffer that modifies its contents in place, making it much faster for repeated concatenation.

    Intern 路 Junior 路 Performance
  • C#Easy

    What is the difference between const and readonly in C#?

    A const is a compile-time constant that must be assigned where it is declared, while a readonly field can be assigned at declaration or in the constructor, so its value can be decided at runtime.

    Junior 路 Mid-level 路 Programming Fundamentals
  • C#Medium

    What is LINQ in C# and what is deferred execution?

    LINQ (Language Integrated Query) lets you query collections, databases and XML with a consistent syntax, and deferred execution means a query does not run when you define it but when you enumerate the results.

    Junior 路 Mid-level 路 Functions & Scope