StructuralC#verifiedVerified

Adapter Pattern in C#

Converts the interface of a class into another interface that clients expect, allowing incompatible interfaces to work together.

How to Implement the Adapter Pattern in C#

1Step 1: Target interface the client expects

public interface IJsonLogger
{
    void Log(string json);
}

2Step 2: Adaptee with an incompatible interface

public class XmlLogger
{
    public void WriteXml(string xml) =>
        Console.WriteLine($"XML: {xml}");
}

3Step 3: Adapter wraps the adaptee to match the target interface

public class XmlToJsonAdapter(XmlLogger xmlLogger) : IJsonLogger
{
    public void Log(string json)
    {
        // Convert JSON to XML (simplified)
        var xml = $"<log>{json}</log>";
        xmlLogger.WriteXml(xml);
    }
}

4Step 4: Client works with the target interface

public class Application(IJsonLogger logger)
{
    public void DoWork() =>
        logger.Log("{\"action\": \"doWork\", \"status\": \"ok\"}");
}

// Usage:
// var adapted = new XmlToJsonAdapter(new XmlLogger());
// var app = new Application(adapted);
// app.DoWork();

Adapter Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Adapter Pattern in the Real World

A travel power adapter lets your American laptop plug (client) work in a European wall socket (adaptee) without modifying either. The adapter speaks both “languages”, translating the two-pin plug to the two-round-pin socket, making them interoperable without any changes on either side.