# Adapter: Making Incompatible Interfaces Work Together

In software development, we rarely build everything from scratch. Applications often depend on existing libraries, third-party services and legacy systems. These dependencies can provide valuable functionality, but integrating them is not always straightforward.

Imagine that you are working on a ticket-management application. The application already has an established way of calculating response deadlines for support tickets. It expects an SLA calculator that accepts a complete `Ticket` object and returns a `DateTimeOffset`.

However, the organisation has acquired an existing SLA calculation library. The library contains years of business rules and has been used successfully in another system. Replacing it would mean duplicating business logic and potentially introducing errors.

There is just one problem: its interface does not match what the application expects.

The application expects something like this:

```csharp
public interface ITicketSlaCalculator
{
    DateTimeOffset CalculateResponseDeadline(Ticket ticket);
}
```

The existing library exposes something closer to this:

```csharp
DateTimeOffset GetResponseDueDate(
    DateTimeOffset openedAt,
    int priorityCode,
    string agreementCode);
```

Both interfaces represent the same general capability, but they communicate in different ways.

We could modify the application to understand the legacy library, or we could change the library itself. Neither option is particularly attractive, especially if the library is maintained by another organisation or cannot be modified.

Instead, we can introduce a layer that translates between the two interfaces.

This is where the **Adapter pattern** becomes useful.

## What is the Adapter pattern?

The Adapter pattern is a structural design pattern that allows objects with incompatible interfaces to work together.

It introduces an intermediary object that implements the interface expected by the client while wrapping an existing service. When the client makes a request, the adapter translates that request into a form the wrapped service understands.

The original service remains unchanged, and the client continues working with the interface it already knows.

The important idea is that the adapter changes how an object is accessed, not necessarily what the underlying object does.

In our ticket-management example, the adapter allows the application to use the existing SLA library without forcing the rest of the application to understand its API.

## Understanding the participants

The Adapter pattern has four main participants:

| Participant | Responsibility | Ticket-management example |
| --- | --- | --- |
| Client | Contains business logic that needs a service. | `TicketAssignmentService` |
| Target interface | Defines the interface expected by the client. | `ITicketSlaCalculator` |
| Adaptee | Provides the existing functionality through an incompatible interface. | `LegacySlaEngine` |
| Adapter | Implements the target interface and translates requests for the adaptee. | `LegacySlaCalculatorAdapter` |

The relationship is straightforward:

1. The client depends on the target interface.
2. The adapter implements that interface.
3. The adapter holds a reference to the adaptee.
4. The adapter translates calls from the client into calls understood by the adaptee.

The client does not need to know that an adapter is involved. It simply works with the interface it was designed to use.

## Implementing Adapter in C#

Let's return to our ticket-management application and implement the solution.

### 1\. Define the application interface

The application should depend on an abstraction that represents its own requirements.

Our `ITicketSlaCalculator` interface provides a consistent contract for calculating response deadlines.

```csharp
public interface ITicketSlaCalculator
{
    DateTimeOffset CalculateResponseDeadline(Ticket ticket);
}
```

For context, assume our domain model contains the following types:

```csharp
public enum TicketPriority
{
    Low,
    Normal,
    High,
    Critical
}

public enum SupportPlan
{
    Standard,
    Premium
}

public sealed record Ticket(
    DateTimeOffset CreatedAt,
    TicketPriority Priority,
    SupportPlan SupportPlan);
```

The application does not need to know how an external library represents priorities or support agreements. It works with domain concepts that make sense within the ticket-management system.

### 2\. Understand the existing service

Our existing SLA library exposes a different contract:

```csharp
public interface ILegacySlaEngine
{
    DateTimeOffset GetResponseDueDate(
        DateTimeOffset openedAt,
        int priorityCode,
        string agreementCode);
}
```

This interface represents the public API of the legacy integration. In a real application, it could be supplied by a third-party library or implemented by a small wrapper around a vendor's concrete SDK class.

Notice the differences:

- The application passes a complete `Ticket` object.
- The legacy service expects individual values.
- The application uses an enum for priority.
- The legacy service expects an integer priority code.
- The application uses a `SupportPlan` enum.
- The legacy service expects a string agreement code.

We need to translate these differences without spreading legacy-specific knowledge throughout the application.

### 3\. Create the adapter

The adapter implements `ITicketSlaCalculator` and receives an instance of `ILegacySlaEngine` through its constructor.

```csharp
public sealed class LegacySlaCalculatorAdapter
    : ITicketSlaCalculator
{
    private readonly ILegacySlaEngine _legacySlaEngine;

    public LegacySlaCalculatorAdapter(
        ILegacySlaEngine legacySlaEngine)
    {
        _legacySlaEngine = legacySlaEngine;
    }

    public DateTimeOffset CalculateResponseDeadline(
        Ticket ticket)
    {
        ArgumentNullException.ThrowIfNull(ticket);

        var priorityCode = MapPriority(ticket.Priority);

        var agreementCode = MapSupportPlan(
            ticket.SupportPlan);

        return _legacySlaEngine.GetResponseDueDate(
            ticket.CreatedAt,
            priorityCode,
            agreementCode);
    }

    private static int MapPriority(
        TicketPriority priority)
    {
        return priority switch
        {
            TicketPriority.Critical => 1,
            TicketPriority.High => 2,
            TicketPriority.Normal => 3,
            TicketPriority.Low => 4,
            _ => throw new ArgumentOutOfRangeException(
                nameof(priority),
                priority,
                "Unsupported ticket priority.")
        };
    }

    private static string MapSupportPlan(
        SupportPlan supportPlan)
    {
        return supportPlan switch
        {
            SupportPlan.Standard => "STD",
            SupportPlan.Premium => "PRM",
            _ => throw new ArgumentOutOfRangeException(
                nameof(supportPlan),
                supportPlan,
                "Unsupported support plan.")
        };
    }
}
```

The adapter performs three important tasks.

**First, it accepts the interface expected by the application.**

By implementing `ITicketSlaCalculator`, it can be used anywhere the application expects an SLA calculator.

**Second, it translates the application data into the format expected by the legacy service.**

The `MapPriority()` and `MapSupportPlan()` methods convert domain enums into the values required by the existing library.

**Third, it delegates the actual calculation to the legacy service.**

The adapter does not reimplement the SLA calculation. It simply translates the request and forwards it to the existing service.

This distinction matters. The responsibility of the adapter is integration, not duplicating the business logic of the system it wraps.

### 4\. Let the client depend on the abstraction

Now consider a service responsible for assigning tickets and obtaining their response deadlines.

```csharp
public sealed class TicketAssignmentService
{
    private readonly ITicketSlaCalculator _slaCalculator;

    public TicketAssignmentService(
        ITicketSlaCalculator slaCalculator)
    {
        _slaCalculator = slaCalculator;
    }

    public DateTimeOffset GetResponseDeadline(
        Ticket ticket)
    {
        return _slaCalculator.CalculateResponseDeadline(
            ticket);
    }
}
```

Notice that `TicketAssignmentService` knows nothing about `ILegacySlaEngine` or `LegacySlaCalculatorAdapter`.

It only knows about `ITicketSlaCalculator`.

That is the real benefit of the pattern. We have isolated the integration details behind an abstraction that belongs to our application.

If the organisation replaces the legacy library with a different SLA provider, we can introduce another adapter without changing the ticket assignment workflow.

## Object adapters and class adapters

The GoF describes two approaches to implementing the Adapter pattern: object adapters and class adapters.

**Object Adapter**

An object adapter uses composition. It implements the target interface and holds a reference to the adaptee.

This is the approach used in our C# example.

The adapter receives an existing `ILegacySlaEngine` instance through its constructor and delegates calls to it.

Object adapters are generally more flexible because they can wrap existing instances without requiring the adaptee to be changed or inherited from.

**Class Adapter**

A class adapter uses inheritance to adapt one class to another interface. The classic GoF implementation relies on multiple inheritance, allowing the adapter to inherit from both the adaptee and the target type.

C# does not support multiple inheritance of classes. However, a C# class can inherit from one adaptee class and implement a target interface.

For example:

```csharp
public sealed class LegacySlaCalculatorAdapter
    : LegacySlaEngine, ITicketSlaCalculator
{
    public DateTimeOffset CalculateResponseDeadline(
        Ticket ticket)
    {
        // Translate the ticket and call inherited
        // legacy functionality.
    }
}
```

**Important:** This example assumes `LegacySlaEngine` is a concrete or abstract base class that exposes the legacy functionality. It is not the `ILegacySlaEngine` interface defined in Step 2. The adapter inherits from the class and implements the application's target interface.

This inheritance-based approach can work when the adaptee is designed for inheritance. However, it is less flexible: it cannot wrap an existing service instance, cannot inherit from a sealed class, and creates a stronger relationship with the adaptee's implementation.

For most application-level integrations in C#, composition is the more practical choice.

## When should you use the Adapter pattern?

The Adapter pattern is particularly useful when:

**1\. Integrating legacy systems**

You may need to use an existing system that works well but exposes an interface that does not fit your application's architecture.

Rather than rewriting or modifying the legacy system, an adapter can translate between its API and the interface your application expects.

**2\. Working with third-party libraries**

External libraries often have their own naming conventions, data structures and method signatures.

An adapter allows you to isolate those differences instead of allowing third-party types to spread throughout your application.

**3\. Replacing an existing implementation**

Suppose your ticket-management application currently uses one external SLA provider, but the organisation decides to move to another.

You can introduce a new adapter that implements `ITicketSlaCalculator` and communicates with the replacement provider.

The client remains unchanged because its dependency is still the same abstraction.

**4\. Reusing functionality that cannot be modified**

Sometimes a useful class already exists, but its interface does not match the rest of your system. An adapter allows you to reuse that functionality without modifying the original class.

## Advantages and trade-offs

Like every design pattern, Adapter introduces benefits as well as costs.

**Advantages**

- **Promotes loose coupling:** Clients depend on an application-facing abstraction rather than a concrete external implementation.
- **Encourages reuse:** Existing libraries and legacy systems can be integrated without rewriting their functionality.
- **Protects the application from external changes:** Changes to an external API can often be contained within the adapter.
- **Improves maintainability:** Translation logic is centralised rather than repeated throughout the application.

**Disadvantages**

- **Introduces additional classes:** Each adapter adds code and another component developers need to understand.
- **Can hide integration complexity:** An adapter may make two interfaces look compatible even when their underlying behaviours differ.
- **Requires careful translation:** Incorrect mapping of values, data types, exceptions or units can introduce subtle bugs.
- **Does not solve every compatibility problem:** Some differences involve conflicting business rules or workflows that cannot be resolved through simple method translation.

The last point is particularly important.

An adapter should not silently discard information or invent behaviour just to make two interfaces appear compatible. If the external system has fundamentally different business rules, those differences need to be addressed explicitly.

The objective is not to hide every difference. It is to isolate and manage the differences that can be translated safely.

## Adapter in modern .NET applications

The Adapter pattern fits naturally into applications built with [ASP.NET](http://ASP.NET) Core and dependency injection.

Instead of manually constructing the adapter wherever it is required, we can register it with the dependency injection container.

For example:

```csharp
builder.Services.AddScoped<
    ILegacySlaEngine,
    LegacySlaEngineClient>();

builder.Services.AddScoped<
    ITicketSlaCalculator,
    LegacySlaCalculatorAdapter>();

builder.Services.AddScoped<TicketAssignmentService>();
```

Here, `LegacySlaEngineClient` represents the implementation that communicates with the existing SLA library or service.

When `TicketAssignmentService` is created, dependency injection supplies an implementation of `ITicketSlaCalculator`. The container resolves `LegacySlaCalculatorAdapter` and provides its `ILegacySlaEngine` dependency.

The application does not need to know how the adapter is constructed.

If the legacy service is an HTTP API, .NET's `IHttpClientFactory` can also help configure and manage the underlying HTTP client. Typed HTTP clients are useful for encapsulating communication with a particular endpoint, while the Adapter can still translate that client's contract into the abstraction expected by the application.

It is important to distinguish the two concepts:

- **Adapter** is a design pattern that translates between incompatible interfaces.
- **Dependency Injection** is a technique for supplying dependencies to objects.
- `IHttpClientFactory` is a .NET facility for creating and configuring `HttpClient` instances.

They can work together, but they solve different problems.

## Adapter vs Decorator, Facade and Proxy

Adapter is sometimes confused with other structural patterns because all four can involve an intermediary object.

However, their intentions are different.

| Pattern | Primary intention |
| --- | --- |
| Adapter | Makes an incompatible interface usable by a client. |
| Decorator | Adds responsibilities to an object without changing its interface. |
| Facade | Provides a simpler interface to a complex subsystem. |
| Proxy | Controls access to another object. |

The key question is what the intermediary is trying to achieve.

If it translates one interface into another, think Adapter.

If it adds behaviour while preserving the existing interface, think Decorator.

If it simplifies interaction with several components, think Facade.

If it controls access to an object, think Proxy.

Understanding the intention behind each pattern is more useful than memorising their class structures.

## Conclusion

The Adapter pattern provides a practical solution to a common software development problem: integrating components that were not designed to work together.

Rather than modifying existing systems or allowing their implementation details to spread throughout an application, we can introduce an adapter that translates between their interfaces.

In our ticket-management example, `LegacySlaCalculatorAdapter` allows the application to continue working with `ITicketSlaCalculator` while reusing an existing SLA engine.

The broader lesson is that integrating external systems does not have to mean compromising the internal design of your application.

However, not every integration needs an adapter. When two components already have compatible interfaces, adding another layer simply creates unnecessary complexity.

The value of the pattern comes from isolating a genuine compatibility problem, not from introducing another class for its own sake.

Next, we'll explore the **Bridge pattern**, which addresses a different structural challenge: separating an abstraction from its implementation so that both can evolve independently.

## Further reading

1. Alexander Shvets — *Dive Into Design Patterns*. The primary reference for the pattern's intent, participants and object-adapter structure.
2. Vaskaran Sarcar — *Design Patterns in C#, 2nd Edition*, Apress, 2020. A C#-focused discussion of object adapters, inheritance-based adapters and implementation trade-offs.
3. Microsoft Learn — [Service registration (dependency injection) in .NET](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/service-registration).
4. Microsoft Learn — [Use the IHttpClientFactory](https://learn.microsoft.com/en-us/dotnet/core/extensions/httpclient-factory).
