Adapter Pattern in C# – Real-Time Example (3rd-Party API Integration)

What is Adapter Pattern?

The Adapter Pattern is a structural design pattern that converts one interface into another so that incompatible classes can work together.

It acts as a bridge between your system and an external/legacy system.


Why Use Adapter Pattern?

  • Integrate third-party or legacy systems
  • Avoid modifying existing code
  • Provide a consistent interface to clients
  • Improve reusability

Real-Time Scenario

You have your system expecting:


IPayment.Pay()

But a third-party service provides:


MakePayment()

👉 Interfaces don’t match → Adapter solves this


Implementation

Step 1: Target Interface (Your System)


public interface IPayment
{
    void Pay();
}

Step 2: Third-Party Service (Incompatible)


public class ThirdPartyPayment
{
    public void MakePayment()
    {
        Console.WriteLine("Paid via third-party");
    }
}

Step 3: Adapter (Bridge)


public class PaymentAdapter : IPayment
{
    private readonly ThirdPartyPayment _thirdParty;

    public PaymentAdapter(ThirdPartyPayment thirdParty)
    {
        _thirdParty = thirdParty;
    }

    public void Pay()
    {
        _thirdParty.MakePayment();
    }
}

Usage Example


IPayment payment = new PaymentAdapter(new ThirdPartyPayment());
payment.Pay();

Output


Paid via third-party

Key Concept

Instead of changing third-party code ❌

We adapt it ✔


// Your system calls
payment.Pay();

// Adapter converts it internally
_thirdParty.MakePayment();

Advantages

  • Reuse existing/third-party code
  • No modification of legacy systems
  • Decouples system from external APIs
  • Improves flexibility

Disadvantages

  • Adds extra layer of abstraction
  • Slight increase in complexity
  • Too many adapters can clutter design

When to Use

  • Integrating third-party APIs
  • Working with legacy systems
  • When interfaces don’t match
  • When rewriting code is not feasible

Real Project Mapping (.NET + Angular)

Feature Usage
Payment gateway integration Adapter
External API integration Adapter
Legacy system migration Adapter
Multiple vendor services Adapter

Pro Tip (Advanced .NET Usage)

  • Use Adapter with Dependency Injection
  • Combine with Factory Pattern for dynamic provider selection
  • Helps in switching providers (e.g., Razorpay → Stripe) easily

Summary

Adapter Pattern helps you:

  • Connect incompatible systems
  • Avoid modifying existing code
  • Build flexible integrations

👉 Perfect for 3rd-party APIs, payment gateways, legacy integrations

Comments