In C#, both abstract classes and interfaces handle abstraction differently: abstract classes share base code and state among related types, while interfaces define a contract of capabilities across unrelated types.
Table of Contents
What Are Abstract Classes and Interfaces?
- Abstract class: An uninstantiable class (using
abstract) supporting both abstract and concrete members. - Interface: A contract (using
interface) dictating required members without dictating internal implementation.
Abstract Class vs Interface: Key Differences
| Aspect | Abstract Class | Interface |
|---|---|---|
| Members & State | Abstract and concrete methods/properties; can hold instance or static fields. | Signatures only (though C# 8+ allows default implementations); no instance fields. |
| Modifiers & Setup | Supports standard access modifiers; can define constructors. | Members are implicitly public; cannot have constructors. |
| Inheritance | Single class inheritance only. | Multiple interface implementation supported. |
| Use Case | "Is-a" relationship for shared base logic. | "Can-do" relationship for cross-cutting capabilities. |
When to Use Abstract Class vs Interface
- Abstract class: Best for closely related classes sharing base behavior or state to eliminate duplicate code.
- Interface: Best for defining flexible contracts across disparate, unrelated types.
C# Code Example: Using Both Together
abstract class Animal
{
public string Name;
public abstract void MakeSound();
public void Sleep() { Console.WriteLine("Sleeping..."); }
}
interface IWalker
{
void Walk();
}
class Dog : Animal, IWalker
{
public override void MakeSound() { Console.WriteLine("Bark!"); }
public void Walk() { Console.WriteLine("Dog is walking..."); }
}
How This Example Works
Animalprovides shared state and concrete logic (Sleep()).IWalkerenforces the walking contract.Dogcombines both through single class inheritance and interface implementation.