Difference Between Interface and Abstract Class in C#
Difference Between Interface and Abstract Class in C#
In object-oriented programming with C#, both interfaces and abstract classes are used to achieve abstraction. Though they sound similar, they serve different purposes and are applied in different design scenarios.
๐น What is an Interface?
- An interface defines a contract: what a class must do, without specifying how.
- It contains method signatures, properties, events, or indexers, but no implementation (except default interface methods in C# 8+).
- A class can implement multiple interfaces.
✅ Example:
public interface IAnimal
{
void Speak();
}
๐ธ What is an Abstract Class?
- An abstract class is a partially implemented class.
- It can have both abstract members (without implementation) and concrete members (with implementation).
- Cannot be instantiated directly.
- Supports only single inheritance.
✅ Example:
public abstract class Animal
{
public abstract void Speak(); // abstract
public void Eat() // implemented
{
Console.WriteLine("Eating...");
}
}
๐ Interface vs Abstract Class: Key Differences
| Feature | Interface | Abstract Class |
|---|---|---|
| Inheritance | Supports multiple inheritance | Only single inheritance |
| Implementation | No method bodies (until C# 8+) | Can have both abstract & concrete methods |
| Constructors | Not allowed | Can have constructors |
| Fields | Not allowed | Allowed (with access modifiers) |
| Access Modifiers | All members are public | Supports public, protected, etc. |
| Purpose | Defines capability | Defines base functionality with reuse |
๐ When to Use What?
✅ Use Interface When:
- You need to define capabilities across unrelated classes
- You want to achieve multiple inheritance
- You're working with dependency injection or plug-in systems
✅ Use Abstract Class When:
- Classes share a common base or behavior
- You need to share default code (methods, properties)
- You want to enforce a base contract with some implementation
๐งช Real-world Example
public interface IDriveable
{
void Drive();
}
public abstract class Vehicle
{
public abstract void Start();
public void Fuel()
{
Console.WriteLine("Fueling vehicle...");
}
}
public class Car : Vehicle, IDriveable
{
public override void Start()
{
Console.WriteLine("Car starting...");
}
public void Drive()
{
Console.WriteLine("Car driving...");
}
}
๐ง Summary
Interface ➝ Defines what needs to be done (capability).
Abstract Class ➝ Provides how with reusable code and structure.
Choose interface when you want flexibility and loose coupling. Choose an abstract class when you want to share reusable code in a closely related class hierarchy.

Comments
Post a Comment