Skip to content

Structural and behavioral patterns in C#

Once objects exist, the next design questions are how they fit together and how they share work. Structural patterns deal with composition: making an incompatible class fit an interface (adapter), adding behavior around an object without changing it (decorator), and putting a collection-like interface in front of data access (repository). Behavioral patterns deal with responsibilities and communication: swapping an algorithm at run time (strategy) and notifying interested parties when something changes (observer).

These five patterns appear constantly in .NET code, often without their names: ASP.NET Core middleware is a chain of decorators, IEnumerable comparers are strategies, C# events implement the observer, and EF Core’s DbSet is close to a repository. The samples use one invented OrdersPortal domain. They are C# file-based programs: save as a .cs file and run dotnet run file.cs with the .NET 10 SDK; all were run with SDK 10.0.115.

Pattern Category Use it when
Adapter GoF structural A class you cannot change has the wrong interface for your code.
Decorator GoF structural You need to add caching, logging, retries or authorization around an object.
Repository Enterprise pattern (Fowler, PoEAA) Business code should not depend on how data is stored.
Strategy GoF behavioral One operation has several interchangeable algorithms.
Observer GoF behavioral Several parts of the system must react when one object changes.

Creational patterns (singleton, factory, builder) are on creational patterns.

The Adapter pattern converts the interface of a class into the interface its clients expect. Your checkout code wants IPaymentGateway.ChargeAsync(orderId, amount, currency); one provider’s SDK wants amounts in cents and returns status strings, and a legacy bank terminal is synchronous and returns numeric codes. An adapter implements your interface and translates each call, including units, naming, error codes and sync-to-async differences, so business code never sees the third-party shape.

The usual C# form is the object adapter: the adapter holds an instance of the adaptee (composition) and implements the target interface. The class adapter variant inherits from the adaptee instead; C# allows it only when the target is an interface, and it couples you to the adaptee’s whole public surface, so composition is preferred. Adapters are the natural place for an anti-corruption layer between bounded contexts: they stop another system’s vocabulary leaking into yours. The provider classes in the sample are invented.

// Checkout depends only on IPaymentGateway; each provider SDK is wrapped by an adapter.
IPaymentGateway[] gateways = [new NorthwindPayAdapter(new NorthwindPayClient()), new LegacyBankAdapter(new LegacyBankTerminal())];
foreach (var gateway in gateways)
{
var result = await gateway.ChargeAsync(orderId: 1001, amount: 128.48m, currency: "USD");
Console.WriteLine($"{gateway.GetType().Name,-20} success={result.Success} ref={result.Reference}");
}
// ---------- Target: the interface your application wants ----------
public sealed record PaymentResult(bool Success, string Reference);
public interface IPaymentGateway
{
Task<PaymentResult> ChargeAsync(int orderId, decimal amount, string currency);
}
// ---------- Adaptees: third-party APIs with their own shapes (invented) ----------
public sealed class NorthwindPayClient
{
// Amounts in minor units (cents), lower-case currency, status strings.
public Task<(string Id, string Status)> CreateChargeAsync(long amountInCents, string currency, string metadata) =>
Task.FromResult(($"ch_{metadata}_{amountInCents}", "succeeded"));
}
public sealed class LegacyBankTerminal
{
// Synchronous, numeric response codes, amount as a formatted string.
public int Authorize(string amount, string currencyCode, out string authCode)
{
authCode = $"AUTH-{amount.Replace(".", "")}";
return 0; // 0 = approved
}
}
// ---------- Adapters: translate calls, units and errors ----------
public sealed class NorthwindPayAdapter(NorthwindPayClient client) : IPaymentGateway
{
public async Task<PaymentResult> ChargeAsync(int orderId, decimal amount, string currency)
{
var (id, status) = await client.CreateChargeAsync((long)Math.Round(amount * 100m), currency.ToLowerInvariant(), $"order{orderId}");
return new PaymentResult(status == "succeeded", id);
}
}
public sealed class LegacyBankAdapter(LegacyBankTerminal terminal) : IPaymentGateway
{
public Task<PaymentResult> ChargeAsync(int orderId, decimal amount, string currency)
{
var code = terminal.Authorize(amount.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture), currency, out var auth);
return Task.FromResult(new PaymentResult(code == 0, auth));
}
}

Output:

NorthwindPayAdapter success=True ref=ch_order1001_12848
LegacyBankAdapter success=True ref=AUTH-12848

Pitfalls:

  • Leaky adapters. Returning the SDK’s exception or response types through your interface defeats the purpose; translate errors into your own result or exception types.
  • Business logic in the adapter. Adapters translate; pricing or retry policy belongs elsewhere (retry is a good decorator).
  • Unit conversions. Money in minor units, time zones and culture-specific number formats are the classic bugs; use invariant culture and test the conversions.

The Decorator pattern attaches extra behavior to an object by wrapping it in another object that implements the same interface and delegates to it. Each decorator does one thing (caching, logging, metrics, retries, authorization checks) and decorators stack in any order, so you avoid a subclass for every combination (CachedLoggedProductCatalog, LoggedRetryingProductCatalog…). Callers depend only on the interface and cannot tell how many layers there are.

In .NET you see the idea in ASP.NET Core middleware, DelegatingHandler chains on HttpClient, Stream wrappers such as BufferedStream and GZipStream, and resilience pipelines. The built-in DI container has no Decorate method, so compose decorators with a factory registration (services.AddScoped<IProductCatalog>(sp => new LoggingCatalog(new CachingCatalog(...)))) or use a library such as Scrutor. The order matters: here logging is outermost, so it times cache hits as well as database calls.

using System.Diagnostics;
// Compose: logging wraps caching wraps the real catalog. Callers see only IProductCatalog.
IProductCatalog catalog = new LoggingCatalog(new CachingCatalog(new SlowDatabaseCatalog()));
foreach (var sku in new[] { "KB-101", "KB-101", "MS-220" })
Console.WriteLine($"{sku}: {await catalog.GetPriceAsync(sku):0.00}");
public interface IProductCatalog { Task<decimal> GetPriceAsync(string sku); }
// The real component.
public sealed class SlowDatabaseCatalog : IProductCatalog
{
private readonly Dictionary<string, decimal> _prices = new() { ["KB-101"] = 49.99m, ["MS-220"] = 25.00m };
public async Task<decimal> GetPriceAsync(string sku)
{
await Task.Delay(50); // pretend this is a database round trip
Console.WriteLine($" db: query {sku}");
return _prices[sku];
}
}
// Decorator 1: adds caching, same interface, delegates to the inner component.
public sealed class CachingCatalog(IProductCatalog inner) : IProductCatalog
{
private readonly Dictionary<string, decimal> _cache = [];
public async Task<decimal> GetPriceAsync(string sku)
{
if (_cache.TryGetValue(sku, out var price)) { Console.WriteLine($" cache: hit {sku}"); return price; }
return _cache[sku] = await inner.GetPriceAsync(sku);
}
}
// Decorator 2: adds logging and timing.
public sealed class LoggingCatalog(IProductCatalog inner) : IProductCatalog
{
public async Task<decimal> GetPriceAsync(string sku)
{
var timer = Stopwatch.StartNew();
var price = await inner.GetPriceAsync(sku);
Console.WriteLine($" log: {sku} in {(timer.ElapsedMilliseconds >= 50 ? "50+" : "<50")} ms");
return price;
}
}

Output:

db: query KB-101
log: KB-101 in 50+ ms
KB-101: 49.99
cache: hit KB-101
log: KB-101 in <50 ms
KB-101: 49.99
db: query MS-220
log: MS-220 in 50+ ms
MS-220: 25.00

Pitfalls:

  • Wrong order. A cache outside an authorization decorator returns cached data to callers who were never authorized; put authorization outermost.
  • Large interfaces. Every decorator must implement every member, even the ones it only forwards. Keep decorated interfaces small and focused.
  • Lifetime mismatch. A singleton caching decorator around a scoped inner service captures the scoped instance; align lifetimes or cache in a separate singleton store such as HybridCache.

The Repository pattern, from Martin Fowler’s Patterns of Enterprise Application Architecture (2002), mediates between the domain and data mapping layers with a collection-like interface: get by ID, find by business criteria, add, update. Business code depends on IOrderRepository, written in domain language (GetPendingForCustomerAsync), and knows nothing about SQL or EF Core; the implementation in the infrastructure layer does. Tests and prototypes swap in an in-memory implementation.

EF Core’s DbContext is already a unit of work and each DbSet<T> is already repository-like, so wrapping it in a generic IRepository<T> with GetAll, Add, Update and Delete adds little and often hides EF Core features (projections, AsNoTracking, includes). A repository earns its place when it is specific (one per aggregate, methods named after real queries), when the domain must stay free of persistence code (see layered architecture), or when data comes from several sources. Otherwise, using DbContext directly in a thin application layer is a valid choice.

// Business code talks to IOrderRepository; tests and this demo use an in-memory implementation.
IOrderRepository repository = new InMemoryOrderRepository();
var service = new OrderService(repository);
await service.PlaceAsync(new Order(1001, CustomerId: 7, Total: 128.48m, Status: "Pending"));
await service.PlaceAsync(new Order(1002, CustomerId: 7, Total: 25.00m, Status: "Pending"));
await service.PlaceAsync(new Order(1003, CustomerId: 9, Total: 189.00m, Status: "Pending"));
await service.ShipAsync(1001);
foreach (var order in await repository.GetPendingForCustomerAsync(7))
Console.WriteLine($"Pending for customer 7: {order.Id} ({order.Total:0.00})");
Console.WriteLine($"Order 1001 status: {(await repository.GetByIdAsync(1001))!.Status}");
public sealed record Order(int Id, int CustomerId, decimal Total, string Status);
// Collection-like interface in the domain's language: no IQueryable, no EF Core types.
public interface IOrderRepository
{
Task<Order?> GetByIdAsync(int id, CancellationToken ct = default);
Task<IReadOnlyList<Order>> GetPendingForCustomerAsync(int customerId, CancellationToken ct = default);
Task AddAsync(Order order, CancellationToken ct = default);
Task UpdateAsync(Order order, CancellationToken ct = default);
}
public sealed class OrderService(IOrderRepository orders)
{
public Task PlaceAsync(Order order) => orders.AddAsync(order);
public async Task ShipAsync(int orderId)
{
var order = await orders.GetByIdAsync(orderId) ?? throw new KeyNotFoundException($"Order {orderId}");
await orders.UpdateAsync(order with { Status = "Shipped" });
}
}
// In production this class would wrap EF Core's DbContext (and SaveChangesAsync would be the unit of work).
public sealed class InMemoryOrderRepository : IOrderRepository
{
private readonly Dictionary<int, Order> _orders = [];
public Task<Order?> GetByIdAsync(int id, CancellationToken ct = default) =>
Task.FromResult(_orders.GetValueOrDefault(id));
public Task<IReadOnlyList<Order>> GetPendingForCustomerAsync(int customerId, CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<Order>>(
_orders.Values.Where(o => o.CustomerId == customerId && o.Status == "Pending").OrderBy(o => o.Id).ToList());
public Task AddAsync(Order order, CancellationToken ct = default) { _orders.Add(order.Id, order); return Task.CompletedTask; }
public Task UpdateAsync(Order order, CancellationToken ct = default) { _orders[order.Id] = order; return Task.CompletedTask; }
}

Output:

Pending for customer 7: 1002 (25.00)
Order 1001 status: Shipped

Pitfalls:

  • Returning IQueryable. It leaks query construction (and EF Core behavior) to callers, so the abstraction protects nothing. Return materialized lists or specific result types.
  • SaveChanges in every method. Two repository calls in one use case then commit separately; let the use case or unit of work commit once.
  • Testing against the in-memory fake only. Fakes do not reproduce SQL translation, constraints or transactions; add integration tests against a real database for the repository itself.

The Strategy pattern defines a family of interchangeable algorithms behind one interface and lets the caller (the context) choose one at run time. Discount rules, shipping cost calculations, tax rules per country, export formats and retry back-off curves are typical families. Adding a new algorithm means adding a class, not editing a growing switch, which keeps the context closed for modification and each rule independently testable.

In C#, a strategy is often just a delegate: Func<decimal, decimal> for a one-method rule, or the IComparer<T> you pass to Sort. Use an interface when strategies have several members, a name, or dependencies of their own. With DI, register strategies as keyed services to pick one by configuration, or inject IEnumerable<IDiscountStrategy> to let the context evaluate all of them, as the “best discount” line in the sample does. Strategy is chosen from outside the context; when an object switches its own behavior as its internal state changes, that is the State pattern.

var cart = new Cart(Subtotal: 640.00m, CustomerLoyaltyPoints: 1500);
// Strategies as classes, chosen at run time.
IDiscountStrategy[] strategies = [new NoDiscount(), new LoyaltyDiscount(), new BulkDiscount(threshold: 500m, percent: 15)];
foreach (var strategy in strategies)
Console.WriteLine($"{strategy.Name,-8} discount {strategy.Calculate(cart),7:0.00} pay {new Checkout(strategy).Total(cart),7:0.00}");
// Best-of: the context can combine strategies without knowing their rules.
var best = strategies.MaxBy(s => s.Calculate(cart))!;
Console.WriteLine($"Best for this cart: {best.Name}");
// Strategies as delegates: a lighter option for one-method strategies.
Func<decimal, decimal>[] shipping = [w => w * 0.50m, w => w * 1.50m + 5m];
Console.WriteLine($"Shipping for 4 kg: standard {shipping[0](4m):0.00}, express {shipping[1](4m):0.00}");
public sealed record Cart(decimal Subtotal, int CustomerLoyaltyPoints);
public interface IDiscountStrategy
{
string Name { get; }
decimal Calculate(Cart cart);
}
public sealed class NoDiscount : IDiscountStrategy
{
public string Name => "none";
public decimal Calculate(Cart cart) => 0m;
}
public sealed class LoyaltyDiscount : IDiscountStrategy
{
public string Name => "loyalty";
public decimal Calculate(Cart cart) => cart.Subtotal * (cart.CustomerLoyaltyPoints > 1000 ? 0.10m : 0.05m);
}
public sealed class BulkDiscount(decimal threshold, int percent) : IDiscountStrategy
{
public string Name => "bulk";
public decimal Calculate(Cart cart) => cart.Subtotal >= threshold ? cart.Subtotal * percent / 100m : 0m;
}
// Context: uses whichever strategy it was given.
public sealed class Checkout(IDiscountStrategy discount)
{
public decimal Total(Cart cart) => cart.Subtotal - discount.Calculate(cart);
}

Output:

none discount 0.00 pay 640.00
loyalty discount 64.00 pay 576.00
bulk discount 96.00 pay 544.00
Best for this cart: bulk
Shipping for 4 kg: standard 2.00, express 11.00

Pitfalls:

  • Strategies for two fixed branches. An if that will never grow is clearer than an interface and two classes.
  • The selection switch just moves. If choosing the strategy still needs a switch on strings, move the mapping into DI keys or a dictionary built at startup.
  • Hidden shared state. Strategies registered as singletons must be stateless; pass everything they need as arguments.

The Observer pattern defines a one-to-many dependency: when a subject changes, all registered observers are notified, without the subject knowing what they do. A shipment tracker should not call the email service, the survey scheduler and the audit log by name; they subscribe and react. This keeps the subject small and lets features be added by subscribing rather than editing.

C# has the pattern built in. Events (event EventHandler<T>) are the everyday form: += subscribes, -= unsubscribes, and the subject raises the event with ?.Invoke. The BCL also defines IObservable<T> and IObserver<T>, a push-based contract with OnNext, OnError and OnCompleted whose Subscribe returns an IDisposable to end the subscription; Reactive Extensions (System.Reactive) builds LINQ-style operators on it. Observers run synchronously on the subject’s thread unless you make them asynchronous. Across process or service boundaries, the same idea becomes publish/subscribe messaging with a broker; see event-driven architecture.

var tracker = new ShipmentTracker();
// Subscribe with C# events (the built-in observer mechanism).
EventHandler<ShipmentStatusChanged> notifyCustomer = (_, e) =>
Console.WriteLine($" email: order {e.OrderId} is now {e.Status}");
tracker.StatusChanged += notifyCustomer;
tracker.StatusChanged += (_, e) =>
{
if (e.Status == "Delivered") Console.WriteLine($" survey: scheduled for order {e.OrderId}");
};
tracker.Update(1001, "InTransit");
tracker.Update(1001, "InTransit"); // no change, no notification
tracker.StatusChanged -= notifyCustomer; // unsubscribe to avoid leaks
tracker.Update(1001, "Delivered");
// IObservable<T>/IObserver<T>: the BCL contract, also used by Reactive Extensions.
using var subscription = tracker.Subscribe(new AuditObserver());
tracker.Update(1002, "Delivered");
public sealed record ShipmentStatusChanged(int OrderId, string Status);
public sealed class ShipmentTracker : IObservable<ShipmentStatusChanged>
{
private readonly Dictionary<int, string> _status = [];
private readonly List<IObserver<ShipmentStatusChanged>> _observers = [];
public event EventHandler<ShipmentStatusChanged>? StatusChanged;
public void Update(int orderId, string status)
{
if (_status.GetValueOrDefault(orderId) == status) return;
_status[orderId] = status;
Console.WriteLine($"tracker: {orderId} -> {status}");
var change = new ShipmentStatusChanged(orderId, status);
StatusChanged?.Invoke(this, change);
foreach (var observer in _observers.ToArray()) observer.OnNext(change);
}
public IDisposable Subscribe(IObserver<ShipmentStatusChanged> observer)
{
_observers.Add(observer);
return new Unsubscriber(() => _observers.Remove(observer));
}
private sealed class Unsubscriber(Action remove) : IDisposable
{
public void Dispose() => remove();
}
}
public sealed class AuditObserver : IObserver<ShipmentStatusChanged>
{
public void OnNext(ShipmentStatusChanged value) => Console.WriteLine($" audit: {value}");
public void OnError(Exception error) { }
public void OnCompleted() { }
}

Output:

tracker: 1001 -> InTransit
email: order 1001 is now InTransit
tracker: 1001 -> Delivered
survey: scheduled for order 1001
tracker: 1002 -> Delivered
survey: scheduled for order 1002
audit: ShipmentStatusChanged { OrderId = 1002, Status = Delivered }

Pitfalls:

  • Memory leaks from forgotten subscriptions. The subject holds a reference to every handler, so a long-lived subject keeps short-lived subscribers alive. Unsubscribe (-= or dispose the subscription) when the observer’s lifetime ends.
  • One slow or failing observer blocks the rest. Event handlers run in sequence on the caller’s thread and an exception stops later handlers. Catch per handler, or hand work to a queue.
  • async void handlers. Exceptions in them crash the process and the subject cannot await them; prefer an explicit async notification interface or a channel.
Situation Pattern
A library or legacy class has the wrong interface Adapter
Add cross-cutting behavior to an existing interface without touching it Decorator
Several algorithms for the same job, picked by configuration or data Strategy
Several independent reactions to one change, in the same process Observer (events)
The same, across services Publish/subscribe messaging
Domain code must not depend on data storage Repository, or a thin application layer over DbContext for simple apps

Adapter and decorator both wrap an object; the difference is intent. An adapter changes the interface to one the client expects; a decorator keeps the interface and adds behavior.

What is the difference between an adapter and a decorator? Both wrap another object. An adapter exposes a different interface from the wrapped object, translating calls; a decorator exposes the same interface and adds behavior before or after delegating, so decorators can be stacked transparently.

Is a generic repository over EF Core a good idea? Usually not on its own: DbContext is already a unit of work and DbSet<T> already a repository, and a generic wrapper hides useful EF Core features. Specific repositories per aggregate, with query methods named in domain language, are worthwhile when the domain must be persistence-ignorant or data comes from several stores.

How does the Strategy pattern relate to the open/closed principle? New behavior is added by writing a new strategy class and registering it; the context code that uses strategies does not change, so it is open for extension and closed for modification.

Why can C# event handlers cause memory leaks? The event’s delegate list holds strong references to subscribers. If a long-lived publisher outlives subscribers that never unsubscribe, those subscribers cannot be garbage collected.

Senior scenario: OrdersPortal’s product catalog API is slow, and the team wants caching, metrics and retries without touching the catalog class. How do you design it? Keep IProductCatalog small and add three decorators: retry (closest to the real implementation, using a resilience pipeline), caching (with HybridCache and explicit invalidation on price changes), and metrics/logging outermost so it measures what callers experience. Register them with a factory or Scrutor’s Decorate, align lifetimes (the cache store as a singleton, the decorators scoped if the inner service is), and test each decorator alone with a fake inner catalog, plus one integration test of the composed chain.