Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Design Patterns in C#: The .NET Interview Guide: back to the course
    Lesson1 / 20

    Module 1 · Foundations: Patterns, SOLID and Judgment · Lesson 1 of 20

    Design Patterns in .NET Interviews: What They Are, the Patterns You Already Use, and How to Choose One

    Two sort orders, one sort method

    An order screen needs to show Alpha before delta even when customer names use mixed case. Array.Sort can keep doing the sorting; pass it StringComparer.OrdinalIgnoreCase to change how it compares names. The sample below sorts delta, Alpha, charlie, Bravo into Alpha, Bravo, charlie, delta.

    A design pattern is a name for a reusable way to solve a recurring design problem. Here the comparison rule can change without changing the sort. That is Strategy. If a built-in comparer already does the job, a custom interface or class adds more code without solving a new problem.

    What to know first

    The C# Beginner, Intermediate, and Advanced courses cover these foundations. In this course, you practise predicting behavior and defending a design choice.

    If the order screen needs the same comparison but in reverse, what should you change first?

    A Replace the sorting algorithm.
    B Supply a comparer that reverses the same comparison.
    C Register the order screen as a DI singleton.
    D Lowercase all the stored names.
    Show answer

    Correct answer: B

    The ordering rule changes, not the sort method or stored data. A comparer can reverse the same case-insensitive comparison.

    Option A: The sort method can already work with a different comparer.

    Option C: A singleton changes how an object is shared, not how names are ordered.

    Option D: Changing the stored names does not reverse their ordering and needlessly changes data.

    Hint: Which part already defines which of two names comes first?

    Force in the programAPI / shapeDecision to practise
    Add processing while retaining Stream operationsBufferedStream / GZipStream wrappingDecorator-like composition; flush/disposal matters
    Construct a value incrementallyStringBuilderConstruction convenience does not parameterize SQL
    Vary ordering independentlyIComparer<string> / comparer strategyChoose the comparison policy
    Defer constructionLazy<T>Initialization policy is distinct from subject thread safety
    Notify subscribersEvent handlersOwn subscription lifetime and failure behavior
    Pull a limited sequenceyield / Take(4)Only requested items are produced

    Example runtime

    • The example was originally written for .NET 8 and C# 12.
    • .NET 8 reached end of support on November 10, 2026. Use the .NET 10 LTS SDK and its default C# 14 language version for the steps below. See the Microsoft .NET support policy.
    • Keep package auditing enabled and check the packages your project resolves.
    • Version-specific differences are called out where relevant.

    Course path

    • Recognize the force.
    • Refactor one decision boundary.
    • Compare composing and inheritance.
    • Trace state, notification and pipeline failures.
    • Solve the drills and the written mock.

    The parallel architecture case-study course applies these mechanisms to larger trade-offs.

    Code example

    1. With the .NET 10 SDK installed, run dotnet new console --framework net10.0 -o PatternExamples.
    2. Replace PatternExamples/Program.cs with the full example below. Keep the console template's implicit usings enabled.
    3. From the folder containing PatternExamples, run dotnet run --project PatternExamples --configuration Release.

    The program illustrates six pattern roles/idioms without custom pattern classes (apart from a tiny event publisher). Lazy<T> is the deferred-creation analogy described above. The SQL text contains only literals; real queries must parameterize external values, not concatenate them.

    C#Runs
    // Patterns you already use in .NET 8: the BCL is full of them.
    using System.IO.Compression;
    using System.Text;
    
    // Decorator: each Stream wraps another Stream and adds one behaviour.
    var raw = new MemoryStream();
    using (var gzip = new GZipStream(raw, CompressionLevel.SmallestSize, leaveOpen: true))
    using (var buffered = new BufferedStream(gzip))
    using (var writer = new StreamWriter(buffered))
    {
        writer.Write(new string('a', 10_000));
    }
    Console.WriteLine($"Decorator  Stream chain: 10000 chars -> {raw.Length} bytes after GZip");
    
    // Builder: StringBuilder assembles a complex value step by step, ToString() is the build step.
    var sb = new StringBuilder().Append("SELECT * FROM Orders").Append(" WHERE Total > ").Append(100);
    Console.WriteLine($"Builder    {sb}");
    
    // Strategy: the sort algorithm is fixed, the comparison is plugged in.
    string[] names = ["delta", "Alpha", "charlie", "Bravo"];
    Array.Sort(names, StringComparer.OrdinalIgnoreCase);
    Console.WriteLine($"Strategy   {string.Join(",", names)}");
    
    // Proxy (virtual proxy): Lazy<T> stands in for an expensive object until first use.
    var created = 0;
    var report = new Lazy<string>(() => { created++; return "expensive report"; });
    Console.WriteLine($"Proxy      created before Value: {created}, after: {(report.Value.Length > 0 ? created : -1)}");
    
    // Observer: events notify any number of subscribers without knowing them.
    var button = new Button();
    button.Clicked += (_, e) => Console.WriteLine($"Observer   audit handler saw click #{e}");
    button.Clicked += (_, e) => Console.WriteLine($"Observer   metrics handler saw click #{e}");
    button.Click();
    
    // Iterator: yield return builds a lazy IEnumerator for you.
    Console.WriteLine($"Iterator   {string.Join(",", Evens().Take(4))}");
    
    static IEnumerable<int> Evens() { for (var i = 0; ; i += 2) yield return i; }
    
    sealed class Button
    {
        private int _count;
        public event EventHandler<int>? Clicked;
        public void Click() => Clicked?.Invoke(this, ++_count);
    }
    Output
    Decorator  Stream chain: 10000 chars -> 52 bytes after GZip
    Builder    SELECT * FROM Orders WHERE Total > 100
    Strategy   Alpha,Bravo,charlie,delta
    Proxy      created before Value: 0, after: 1
    Observer   audit handler saw click #1
    Observer   metrics handler saw click #1
    Iterator   0,2,4,6

    Sample output (.NET 8, Release)

    The original .NET 8 Release run produced the same seven lines shown above.

    Code walkthrough

    • Decorator: a StreamWriter writes into a BufferedStream, which writes into a GZipStream, which writes into a MemoryStream. BufferedStream and GZipStream are Stream decorators; StreamWriter is a TextWriter adapter over the byte-stream chain. The sample records 52 bytes for 10,000 repeated characters with this wrapper/flush sequence. Exact compressed length depends on compressor/runtime details and flushing; it is not an API guarantee or a comparison benchmark. Disposal flushes the writer/buffer and finishes GZip; leaveOpen: true keeps the underlying memory stream readable.
    • Builder: StringBuilder.Append collects parts; ToString() (called by interpolation) produces the final string.
    • Strategy: Array.Sort is the fixed algorithm and StringComparer.OrdinalIgnoreCase is the plugged-in comparison, so Alpha,Bravo,charlie,delta sorts ignoring case.
    • Proxy analogy: the Lazy<string> holder defers creation until .Value; it is not itself a string-compatible proxy. The factory runs zero times before that access and once after it in this sample. Default initialization synchronization does not make a mutable created object thread-safe.
    • Observer: two handlers subscribe to Clicked; the publisher does not depend on their concrete types. Ordinary multicast delegate invocation runs them synchronously in invocation-list order here; an uncaught exception in the first would prevent the second from running. This tiny sample is not an isolated, asynchronous or durable event bus. Its ++_count is inside the null-conditional invocation, so it increments only when a subscriber exists; separate the increment if counting every click is required.
    • Iterator: Take(4) pulls only 0,2,4,6 on demand. The loop has no explicit end, but int is bounded: much later arithmetic wraps in unchecked execution or throws with checked overflow. Do not read it as an unbounded increasing mathematical integer sequence.

    Reason from the example

    A design pattern is a named, reusable shape for solving a recurring design problem in a context. The name is the valuable part: "put a decorator around the repository" says in a few words what would otherwise take a whiteboard. Patterns are not code you copy; they are vocabulary plus a known list of trade-offs.

    In modern C#, many patterns have become language features or framework features. Events are Observer, IEnumerable<T> with yield return is Iterator, the DI container is a factory with lifetime management, and ASP.NET Core middleware is Chain of Responsibility. Interviewers for .NET roles care less about UML and more about whether you can spot the pattern in real code, say why it is there, and say when it would be overkill.

    Design choices and limits

    • Where the catalogue comes from. Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson, Vlissides, 1994, the "Gang of Four") catalogued 23 patterns in three families. This course covers selected patterns used in .NET, plus the judgment around them.
    • The three families:
      • Creational patterns control how objects are created, so the caller does not depend on concrete classes or on a complicated construction sequence.
      • Structural patterns control how objects are composed: wrapping, adapting, simplifying or grouping objects behind a common interface.
      • Behavioral patterns control how responsibility and communication are distributed: who decides, who is notified, and which algorithm runs.
    • Every pattern has four parts. Use these when you explain one in an interview:
      1. a name;
      2. the problem and the context in which it appears;
      3. the solution shape (participants and how they collaborate);
      4. the consequences: what you gain and what you pay.
    • Patterns already in the BCL and ASP.NET Core (the code illustrates six familiar pattern roles/idioms). These are useful mappings, not a claim that every API reproduces all participants in the original GoF diagram:
      • Decorator: Stream subclasses wrap streams (GZipStream, BufferedStream, CryptoStream), and DelegatingHandler wraps HttpClient handlers.
      • Builder-style APIs: StringBuilder, UriBuilder, WebApplication.CreateBuilder, IHostBuilder. Stepwise construction is the shared idea; StringBuilder alone is not the full GoF director/builder arrangement.
      • Strategy: IComparer<T>, IEqualityComparer<T>, StringComparer, JsonNamingPolicy.
      • Proxy: EF Core lazy-loading proxies, generated gRPC clients (remote proxy), DispatchProxy. Lazy<T> illustrates deferred creation used inside a virtual proxy, but is a holder exposing .Value, not a transparent implementation of T's interface.
      • Observer: C# events, IObservable<T>, IOptionsMonitor<T>.OnChange, IChangeToken.
      • Iterator: IEnumerable<T> and IAsyncEnumerable<T> with yield return.
      • Chain of Responsibility: ASP.NET Core middleware and MediatR pipeline behaviours.
      • Factory: IHttpClientFactory, ILoggerFactory, DbProviderFactory, and the DI container itself.
      • Template Method-style hooks: the BackgroundService lifecycle invokes overridable ExecuteAsync; framework algorithms can orchestrate overridable Stream/JsonConverter<T> operations. Inheritance or a virtual method alone is not proof of a fixed algorithm skeleton.
      • Visitor: ExpressionVisitor, Roslyn's CSharpSyntaxWalker.
    • How to choose, in order:
      1. Name the force. What is changing or will change? "We add a carrier every quarter" is a force; "we might need flexibility" is not.
      2. Try the plain solution first. A method, a switch expression, a delegate or a record often solves it. When not to use patterns is about this.
      3. Match force to pattern. Varying algorithm: Strategy. Behaviour depends on lifecycle state: State. Add behaviour without editing a class: Decorator. Incompatible API: Adapter. Many components talking to each other: Mediator. Cross-cutting steps around every request: Chain of Responsibility.
      4. State the cost. More types, more indirection, harder navigation in the IDE. A pattern that does not pay for its indirection is an anti-pattern.
    • What "use a pattern" means in modern .NET: often composition, delegates and DI registrations rather than elaborate class hierarchies. Choose singleton/scoped/transient lifetimes from ownership and concurrency requirements; scoped/transient are not Singleton equivalents. A DI singleton is normally one cached instance per registration within a root service provider, not one across every provider, process or machine, and the instance must support concurrent use when shared. IEnumerable<T> injection supplies registered implementations, while keyed selection and ordering may still need an explicit policy. A delegate can replace a one-method interface when its contract and state needs fit.

    Real-world .NET usage

    • Reading a large compressed file is a decorator chain: FileStream → GZipStream → StreamReader.
    • IHttpClientFactory can compose configured DelegatingHandler decorators such as logging, resilience and authentication. It does not automatically add every listed policy; registration/order and safe retry semantics remain application choices.
    • services.AddHttpClient<T>() registers factory-managed typed-client construction; AddSingleton<T>() configures a DI lifetime with the scope/ownership limits above. Middleware registration such as app.Use(...) builds a request chain; a stage may short-circuit rather than call the next stage.
    • EF Core's query translation walks LINQ expression trees with ExpressionVisitor.

    Trade-offs

    Benefit of using a patternCost you pay
    A shared name shortens design discussions and code reviewsReaders must know the name, or it becomes jargon
    Known extension points (add a class instead of editing a switch)More types and files; logic is spread out
    Easier testing through interfacesIndirection: "Go to definition" lands on an interface
    Proven consequences, documented pitfallsApplying a pattern "in case" adds cost with no benefit

    Failure modes

    • Starting from a pattern name ("let's use Abstract Factory") instead of from a problem.
    • Reimplementing what .NET already provides: a hand-written Singleton instead of AddSingleton, an observer list instead of an event, a pipeline instead of middleware.
    • Pattern-shaped code without the pattern's benefit: an interface with one implementation that will never vary, created only "for testability" when the class has no dependencies to fake.
    • Memorising UML diagrams without being able to say what problem the pattern solves.

    Interview angle

    When asked "Which design patterns have you used?", do not list names. Pick two and tell a short story each: the force, the pattern, the result, and the cost. Example: "Our checkout had a growing switch for shipping carriers. I moved each carrier to an IShippingStrategy, registered them in DI, and the calculator picks one by key. Adding a carrier became a new class plus a registration, and each carrier got its own unit tests. The cost was more files, which was fine because carriers changed monthly."

    Then show you know the platform: "We also use Decorator through DelegatingHandler for retries, and Chain of Responsibility through middleware."

    Practise the decision

    Attempt before comparing

    1. What is a design pattern, in one sentence?
    1. Name the three GoF families and give a .NET example for each.
    1. Is a DI container a design pattern?
    1. How do you decide that a pattern is not worth it?
    1. Which pattern does IEnumerable<T> with yield return implement, and what is the practical benefit?

    Hint if needed

    Recognizing a familiar API is not enough: say what the caller can vary and what that API does not promise.

    Compare the reasoning

    1. Answer: A named, reusable solution shape for a recurring design problem in a given context, together with its known consequences; it is a vocabulary and a set of trade-offs, not a piece of code to copy.
    1. Answer: Creational (IHttpClientFactory, StringBuilder), structural (GZipStream as a decorator over Stream, or an actual interface-implementing proxy such as DispatchProxy), behavioral (C# events as Observer, IComparer<T> as Strategy, middleware as Chain of Responsibility).
    1. Answer: It is an implementation of Inversion of Control that bundles several patterns: a factory that builds object graphs, lifetime management including container-scoped singleton registrations, and a registry. It does not enforce a process-wide sole instance or make shared services thread-safe. Dependency Injection itself is a technique (passing dependencies in) that makes Strategy, Decorator and others cheap to apply.
    1. Answer: If no force exists yet (only one variant, no expected change, no testing seam needed), the plain solution wins. Count the added types and indirection and compare them with the concrete change they make easier. Refactor to the pattern when the second or third variant actually appears.
    1. Answer: Iterator. The compiler generates the state machine, so callers can enumerate lazily without knowing the collection's structure, and infinite or expensive sequences produce only the items that are pulled.

    Lookup

    Force → pattern

    • Object creation varies or is complex → Factory Method, Abstract Factory, Builder.
    • One shared instance per container registration → a Singleton lifetime in DI; design for concurrency.
    • Copy a configured object → Prototype-like copying (record with is shallow by default; referenced mutable state can remain shared).
    • Incompatible API → Adapter. Too many subsystems → Facade.
    • Add behaviour without editing → Decorator. Control access or delay creation → Proxy.
    • Tree of parts and wholes → Composite.
    • Interchangeable algorithm → Strategy. Behaviour by lifecycle state → State.
    • Fan-out notifications → Observer. Many-to-many coordination → Mediator.
    • Request as an object (queue, undo) → Command. Ordered handlers → Chain of Responsibility.
    • Fixed skeleton, varying steps → Template Method. Operations over a fixed type hierarchy → Visitor or pattern matching.
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 24 Nov 2026 ·