SkillPilotAI

Design patterns in C#

Design patterns are named, tested solutions to design problems that keep coming back. Using one online-shop checkout, this note covers Strategy, Factory, Builder, Decorator, Adapter, Observer, Singleton (Lazy<T> vs AddSingleton) and the Result pattern.

71.1 The problem: everything in one method

  • PlaceOrder takes an amount and a coupon code; a switch applies the discount and the method itself does new SmsSender().
  • Every new coupon means editing the switch (violates Open/Closed).
  • The SMS sender is hard-coded inside, so it cannot be swapped or faked in a test.
  • A normal business case (unknown coupon) throws an exception and crashes the app.
C#
PlaceOrder(2000m, "FLAT100");PlaceOrder(1500m, "DIWALI20"); void PlaceOrder(decimal amount, string code){    var total = code switch    {        "FLAT100" => amount - 100,        "SALE10" => amount * 0.9m,        _ => throw new ArgumentException(            $"Unknown coupon {code}")    };    new SmsSender().Send($"Paid Rs {total}");}
Output
$ dotnet run bug.csSMS: Paid Rs 1900Unhandled exception. System.ArgumentException:Unknown coupon DIWALI20
Why did checkout crash?
  1. 1.Coupon switch: every new coupon = edit this method

  2. 2.new SmsSender(): dependency hard-coded inside

  3. 3.DIWALI20 not in the switch -> ArgumentException

  4. 4.Normal business case becomes an app crash

  5. 5.Fix: patterns split creation, behaviour and failure handling

SOLID says what to aim for; patterns say how

71.2 Strategy: one class per discount

  • Different ways of doing one job go into different classes behind one interface.
  • The caller only knows IDiscount; FlatOff and PercentOff are interchangeable.
  • A new discount = a new class, no edit to existing code.
  • The IPaymentMethod from the SOLID video was this pattern without the name.
C#
interface IDiscount{    decimal Apply(decimal amount);}class FlatOff(decimal off) : IDiscount{    public decimal Apply(decimal a) => a - off;}class PercentOff(int pct) : IDiscount{    public decimal Apply(decimal a)        => a * (100 - pct) / 100;}

71.3 Factory: creation in one place

  • DiscountFactory.Create turns a coupon string into the right IDiscount.
  • ToUpperInvariant() makes the code case-insensitive; an unknown code returns null.
  • The switch still exists, but only in one place instead of inside business logic.
C#
string[] codes = ["FLAT100", "SALE10"];foreach (var code in codes)    Console.WriteLine(DiscountFactory        .Create(code)?.Apply(2000m)); static class DiscountFactory{    public static IDiscount? Create(string code)        => code.ToUpperInvariant() switch        {            "FLAT100" => new FlatOff(100),            "SALE10" => new PercentOff(10),            _ => null        };}
Output
$ dotnet run factory.cs19001800

71.4 Builder: an order step by step

  • Use it when an object has many optional parts (items, coupon, gift wrap) and a big constructor gets confusing.
  • Every step returns the builder itself, so calls chain fluently.
  • Build() does the final validation: an order without items throws InvalidOperationException, so an incomplete object never gets out.
C#
var order = new OrderBuilder()    .AddItem("Mixer Grinder", 2499m)    .AddItem("Steel Bottle", 399m)    .WithCoupon("FLAT100")    .WithGiftWrap()    .Build();Console.WriteLine(order); // inside class OrderBuilderpublic Order Build() => items.Count > 0    ? new(items.Count, items.Sum(i => i.Price),        coupon, giftWrap)    : throw new InvalidOperationException(        "Order needs at least one item");
Output
$ dotnet run builder.csOrder { Items = 2, Total = 2898,  Coupon = FLAT100, GiftWrap = True } # new OrderBuilder().WithGiftWrap().Build()Unhandled exception.System.InvalidOperationException:Order needs at least one item

71.5 Decorator: add behaviour by wrapping

  • LoggingNotifier implements INotifier and wraps another INotifier.
  • It writes the log line and then passes the call to the inner notifier.
  • SmsNotifier is not touched; decorators can be stacked (e.g. Logging around Retry around Sms).
C#
INotifier notifier =    new LoggingNotifier(new SmsNotifier());notifier.Send("Order 101 placed"); class LoggingNotifier(INotifier inner)    : INotifier{    public void Send(string msg)    {        Console.WriteLine($"[log] {msg}");        inner.Send(msg);    }}
Output
$ dotnet run decorator.cs[log] Order 101 placedSMS: Order 101 placed
Decorator call chain
  1. 1.Caller calls notifier.Send("Order 101 placed")

  2. 2.LoggingNotifier writes [log] Order 101 placed

  3. 3.LoggingNotifier calls inner.Send(msg)

  4. 4.SmsNotifier sends SMS: Order 101 placed

Same interface outside, extra behaviour inside

71.6 Adapter: make a third-party SDK fit

  • The old LegacyPayClient takes paise and returns a status string; we cannot change it.
  • Our code wants IPaymentGateway.Pay(decimal rupees) returning bool.
  • The adapter converts rupees to paise, calls the SDK and maps "SUCCESS" to true, like a travel plug adapter.
C#
IPaymentGateway gateway =    new LegacyPayAdapter(new LegacyPayClient());Console.WriteLine(gateway.Pay(1899.50m)); class LegacyPayAdapter(LegacyPayClient client)    : IPaymentGateway{    public bool Pay(decimal rupees)    {        var paise = (long)(rupees * 100);        var status = client.Charge(paise);        return status == "SUCCESS";    }}
Output
$ dotnet run adapter.csLegacyPay: charging 189950 paiseTrue

71.7 Observer: events in C#

  • When an order is placed, stock and email must react, but OrderService must not know about them.
  • In C# the Observer pattern is simply an event: subscribers use +=, the publisher calls Invoke.
  • ?.Invoke avoids a NullReferenceException when nobody has subscribed.
C#
var orders = new OrderService();orders.OrderPlaced += id =>    Console.WriteLine($"Stock updated: {id}");orders.OrderPlaced += id =>    Console.WriteLine($"Email sent: {id}");orders.Place("ORD-101"); class OrderService{    public event Action<string>? OrderPlaced;    public void Place(string id)        => OrderPlaced?.Invoke(id);}
Output
$ dotnet run observer.csStock updated: ORD-101Email sent: ORD-101

71.8 Singleton with Lazy<T>

  • Singleton = only one object of a class in the whole app.
  • A private constructor stops anyone outside from calling new.
  • Lazy<AppConfig> creates the object only when .Value is first read, and it is thread-safe by default.
  • Output shows Loading config... after App started (lazy) and True (same object both times).
C#
Console.WriteLine("App started");Console.WriteLine(AppConfig.Instance.DeliveryFee);Console.WriteLine(ReferenceEquals(    AppConfig.Instance, AppConfig.Instance)); sealed class AppConfig{    static readonly Lazy<AppConfig> instance =        new(() => new AppConfig());    public static AppConfig Instance        => instance.Value;    public decimal DeliveryFee { get; } = 49m;    private AppConfig()        => Console.WriteLine("Loading config...");}
Output
$ dotnet run singleton.csApp startedLoading config...49True

Checkpoint: 100 threads read Instance at the same time. Loading config... prints only once, because Lazy<T> uses a lock by default. A hand-made 'if (instance == null) instance = new ...' can create two objects under races.

C#
Parallel.For(0, 100, _ =>{    var config = AppConfig.Instance;});Console.WriteLine("Done");
Output
$ dotnet run checkpoint.csLoading config...Done

71.9 Comparison: hand-made Instance vs AddSingleton

C#
// Wrong: hidden dependencyclass OrderService{    public decimal Total(decimal amount)        => amount         + AppConfig.Instance.DeliveryFee;}// hidden dependency, fee fixed in tests
C#
// Right: one object, from DI, testablebuilder.Services.AddSingleton<IAppConfig,    AppConfig>(); class OrderService(IAppConfig config){    public decimal Total(decimal amount)        => amount + config.DeliveryFee;}
PointAppConfig.Instance (static)AddSingleton (DI)
Objects in the appOneOne (the container keeps it)
DependencyHidden inside the methodVisible in the constructor
TestingCannot change the delivery feePass a fake IAppConfig easily
VerdictAvoid in servicesPreferred

71.10 Result pattern instead of exceptions

  • An invalid coupon is an expected business case, not an unexpected error.
  • Return Result<T> with Value and Error; IsSuccess is true when Error is null.
  • A null from the factory becomes an error Result; no crash, the caller decides what to show.
  • Keep exceptions for truly unexpected failures (DB down, bug).
C#
var ok = Checkout(2000m, "FLAT100");var bad = Checkout(2000m, "OOPS");Console.WriteLine($"{ok.IsSuccess} {ok.Value}");Console.WriteLine($"{bad.IsSuccess} {bad.Error}"); Result<decimal> Checkout(decimal amount,    string code){    var offer = DiscountFactory.Create(code);    return offer is null        ? new(0, $"Invalid coupon {code}")        : new(offer.Apply(amount), null);}record Result<T>(T? Value, string? Error){ public bool IsSuccess => Error is null; }
Output
$ dotnet run result.csTrue 1900False Invalid coupon OOPS

71.11 Three families of patterns

FamilyDecidesPatterns in this video
CreationalHow an object gets createdFactory, Builder, Singleton
StructuralHow objects connect to each otherDecorator, Adapter
BehavioralHow objects share the workStrategy, Observer

71.12 When to use which

You see...Use
A long switch on a type or codeStrategy + Factory
Many optional parts plus validationBuilder
Need extra behaviour without changing a classDecorator
A third-party API with the wrong shapeAdapter
Many listeners for one happeningObserver (event)
Exactly one shared objectAddSingleton (or Lazy<T> if hand-made)
Expected business failureResult

71.13 Common mistakes

  • Thinking more patterns = better code: every pattern adds a layer; with only one discount a plain method is enough.
  • Thinking Singleton is always bad: the problem is static access; a DI singleton is fine.
  • Hand-made singleton with a null check: not thread-safe, can create two objects.
  • Throwing exceptions for normal business outcomes like an invalid coupon.

71.14 Interview tips

  • Answer 'which patterns have you used?' with examples, not a list of names.
  • Say: Strategy for discounts with a Factory to create them, Decorator for logging, Adapter for a third-party SDK.
  • For a singleton: AddSingleton from DI; Lazy<T> when a hand-made one is really needed (thread-safe).
  • Mention that Observer in C# is just events.
  • Say you return a Result for expected failures and keep exceptions for unexpected ones.