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?

✅ Example:

public interface IAnimal
{
    void Speak();
}

๐Ÿ”ธ What is an Abstract Class?

✅ 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:

✅ 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

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features