Explaining Adapter Pattern Using .NET and C#

Using the Adapter Pattern to Connect Incompatible Interfaces

Abdelmajid BACO
2 min readDec 27, 2022
Photo by Call Me Fred on Unsplash

The adapter pattern is a design pattern that allows two incompatible interfaces to work together.

It can be used as a bridge between two existing implementations and act as a wrapper for an object to make it compatible with another.

In C#, the adapter pattern is implemented using simple class inheritance.

To illustrate this concept, consider a scenario where you have an interface called IShapeOne and two classes called Square and Circle. We need to add a Triangle class that implements IShapeOne but does not behave like Squareor Circle. This is where the adapter pattern can be used.

Here’s an example of how to implement the adapter pattern in C#:

//The first interface
public interface IShapeOne
{
void Draw();
}
//The first interface implementation
public class Circle : IShapeOne
{
public void Draw()
{
Console.WriteLine("Drawing Circle using IShapeOne");
}
}
//The first interface another implementation
public class Square : IShapeOne
{
public void Draw()
{
Console.WriteLine("Drawing Square using IShapeOne");
}
}

//The second interface
public interface IShapeTwo
{
void DrawShape();
}

//The second interface implementation
public class Triangle : IShapeTwo
{
public void DrawShape()
{
Console.WriteLine("Drawing Triangle using IShapeTwo!");
}
}

//Adapter to connect incompatible interfaces
public class TriangleAdapter : IShapeOne
{
private Triangle triangle;

public TriangleAdapter(Triangle t)
{
this.triangle = t;
}

public void Draw()
{
triangle.DrawShape();
}
}

Conclusion

The adapter pattern is a useful design pattern that can be used as a bridge between two existing implementations, allowing two incompatible interfaces to work together. It offers a simple and effective means of creating new features. Furthermore, it can be easily implemented in C# using class inheritance. Ultimately, the adapter pattern is a powerful tool for developing modern applications.

--

--

Abdelmajid BACO
Abdelmajid BACO

Written by Abdelmajid BACO

Senior Full Stack .Net / Angular Developer, Cloud & Azure DevOps, Carrier Manager, Husband, and Father.

No responses yet