Abstract class vs interface in C#
The basic definition
// Interface - a pure contract, no implementation (up to C# 7)
public interface IOrderValidator
{
bool Validate(Order order);
}
// Abstract class - can have an implementation, can be partial
public abstract class OrderProcessorBase
{
protected readonly ILogger _logger;
protected OrderProcessorBase(ILogger logger) // konstruktor - czego interfejs nie ma
{
_logger = logger;
}
public abstract void Process(Order order); // a method WITHOUT an implementation - must be overridden
public void LogProcessing(Order order) // a method WITH an implementation - inherited as is
{
_logger.Log($"Processing order {order.Id}");
}
}
Key difference #1: Multiple inheritance
// ✅ A class can implement MANY interfaces
public class Order : IValidatable, IComparable<Order>, IDisposable
{
public bool Validate() => true;
public int CompareTo(Order other) => 0;
public void Dispose() { }
}
// ❌ A class can inherit from only ONE class (abstract or not)
public class SpecialOrder : OrderProcessorBase, AnotherBaseClass // COMPILE ERROR
{
}
This is the most frequently cited difference in interviews - C# (like most OOP languages other than C++) doesn't support multiple inheritance of classes, but it does support implementing multiple interfaces. This ties directly back to the Interface Segregation Principle from SOLID - which is why it is better to have many small interfaces than to try to "cram" everything into one class hierarchy.
Key difference #2: State (fields)
public abstract class RepositoryBase<T>
{
protected readonly AppDbContext _context; // ✅ An abstract class CAN have fields/state
protected RepositoryBase(AppDbContext context) => _context = context;
}
public interface IRepository<T>
{
// ❌ An interface CANNOT have fields (only properties - without backing fields)
// AppDbContext Context; // compile error
}
An abstract class can hold real state (instance fields) and logic that operates on that state. An interface defines only what the implementing class must expose, not how it stores it.
Key difference #3: Constructors
public abstract class ViewModelBase
{
protected ViewModelBase(ILogger logger) // ✅ a constructor - initialising shared state
{
Logger = logger;
}
protected ILogger Logger { get; }
}
public interface IViewModel
{
// ❌ an interface CANNOT have a constructor
}
This has a real practical consequence - an abstract class can enforce the initialisation of shared dependencies through the constructor (as in ViewModelBase), an interface has no such possibility - the implementing class must take care of initialisation itself.
Key difference #4: Access modifiers
public abstract class OrderProcessorBase
{
public abstract void Process(Order order);
protected virtual void Validate(Order order) { } // protected - available only to derived classes
private void InternalHelper() { } // private - not accessible from outside at all
}
public interface IOrderProcessor
{
void Process(Order order); // wszystko w interfejsie jest implicitly PUBLIC
// protected void Validate(Order order); // since C# 8+ POSSIBLE (default interface methods), but rarely used
}
An abstract class gives full control over visibility (public, protected, private) - an interface traditionally forces everything to be public (although modern C# has partly relaxed this, see below).
Default implementation in interfaces (C# 8+) - blurs the line
public interface ILogger
{
void Log(string message);
// Default implementation - NEW since C# 8.0
void LogError(string message) => Log($"ERROR: {message}"); // an implementation INSIDE the interface
}
public class ConsoleLogger : ILogger
{
public void Log(string message) => Console.WriteLine(message);
// LogError does NOT have to be overridden - it inherits the default implementation
}
This brings interfaces closer to abstract classes (you can have "ready-made" code), but an interface still has no fields/state or constructors - that is the fundamental boundary which default interface methods don't cross.
When to use an abstract class
When the derived classes are closely related and share a common implementation - the classic Template Method Pattern we discussed with Inversion of Control:
public abstract class OrderProcessorBase
{
// Controls the ORDER - common to all subclasses
public void Process(Order order)
{
Validate(order);
Save(order);
Notify(order);
}
protected virtual void Validate(Order order) { /* default validation */ }
protected abstract void Save(Order order); // EVERY subclass MUST provide its own
protected virtual void Notify(Order order) { /* default notification */ }
}
public class StandardOrderProcessor : OrderProcessorBase
{
protected override void Save(Order order) { /* zapis standardowy */ }
// Validate and Notify - inherited unchanged, because the default behaviour fits
}
This shows the strength of an abstract class - the shared logic and the order of execution live in one place, and subclasses supply only what actually differs.
When to use an interface
When you want to define a contract, not necessarily related by a class hierarchy - completely unrelated classes can implement the same interface:
public interface IComparable<T> { int CompareTo(T other); }
public class Order : IComparable<Order> { public int CompareTo(Order other) => 0; }
public class Product : IComparable<Product> { public int CompareTo(Product other) => 0; }
// Order and Product have NOTHING in common apart from this one contract
A pattern we have already seen many times - DI operates precisely on interfaces:
public interface IOrderService { Task<Order> GetOrderAsync(int id); }
services.AddScoped<IOrderService, OrderService>();
An interface is preferred here because it allows easy swapping of implementations (a mock in tests, a different implementation at runtime) - this is exactly the Dependency Inversion Principle from SOLID.
A concrete example - why ViewModelBase is an abstract class and IOrderService is an interface
// An abstract class - because ALL ViewModels share EXACTLY the same SetProperty logic
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
// An interface - because the different implementations (UserService, MockUserService in tests)
// have DIFFERENT logic inside, only the contract connects them
public interface IUserService
{
Task<User> GetUserAsync(string id);
}
ViewModelBase provides ready-made, shared code (the SetProperty implementation) - that is what an interface (before C# 8) couldn't do. IUserService is a pure contract - each implementation does something completely different inside.
You can combine both
public interface IOrderProcessor
{
void Process(Order order);
}
public abstract class OrderProcessorBase : IOrderProcessor // implementuje interfejs
{
public void Process(Order order) // provides the shared implementation
{
Validate(order);
Save(order);
}
protected virtual void Validate(Order order) { }
protected abstract void Save(Order order);
}
public class StandardOrderProcessor : OrderProcessorBase
{
protected override void Save(Order order) { }
}
This is a common, good pattern - an interface as the contract visible from outside (for DI, for mocking in tests), an abstract class as the shared implementation for a family of related classes inside.
Comparison table
| Abstract class | Interface | |
|---|---|---|
| Multiple inheritance | ❌ Only one base class | ✅ Many interfaces at once |
| Fields/state | ✅ Yes | ❌ No (only properties without a backing field) |
| Constructor | ✅ Yes | ❌ No |
| Method implementation | ✅ Any (full, partial, none) | ⚠️ Partially since C# 8 (default methods) |
| Access modifiers | ✅ public/protected/private | Public by default (partly relaxed in C# 8+) |
| When to use | Closely related classes with shared logic (Template Method) | A contract for unrelated classes, DI, testability |
A trick question in an interview
"Can an abstract class have no abstract methods at all?" - Yes, technically it can. The abstract modifier on a class only means "you can't create an instance of this class directly" (new OrderProcessorBase() won't compile) - it can contain only virtual/ordinary methods, without a single abstract one. This is rare in practice (there is usually a reason to force an override), but it shows that an abstract class is above all "don't instantiate me directly, I'm a base for inheritance", regardless of how many abstract methods it has.