📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š .NET Interview Questions

1325 questions for senior .NET engineer interviews, each with a 30-second answer, the full answer, a deep dive, the follow-ups interviewers ask next, and real-world production problems.

Phase 8 — Design Patterns

The GoF creational, structural and behavioural patterns and the enterprise patterns used in modern .NET 10 services, with the judgement to know when a pattern helps and when it is ceremony.

  1. Refactor this shipping cost calculator: a long switch on carrier (AusPost, StarTrack, DHL) that every new carrier edits, with rates hard-coded inside. Turn it into strategies selected by key and registered in DI, show how the result satisfies Open/Closed, how you test it, and when you would leave the switch alone.

    Step-by-step refactor of a carrier switch into keyed shipping strategies: characterisation tests first, IShippingStrategy with a Carrier key, rates moved to options, a context that builds a dictionary once and fails fast on duplicates, DI registration, unit and registration tests, Open/Closed in practice, and when a switch is the better answer.

    Mid-Level Coding Behavioral Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  2. What is the Observer pattern? Explain how C# events, IObservable<T>/IObserver<T> and IOptionsMonitor<T> change notifications implement it, how observers unsubscribe, and how Observer differs from publish/subscribe through a message broker.

    Observer intent and structure, C# events and EventHandler<T>, IObservable<T>/IObserver<T> with IDisposable subscriptions and Rx, IOptionsMonitor<T>.OnChange and change tokens, INotifyPropertyChanged, unsubscribing and the leak risk, synchronous in-process notification vs broker-based pub/sub.

    Junior Theory Behavioral Patterns Β· πŸ”— 3 follow-ups
  3. After a release, your ASP.NET Core API's memory climbs by about 200 MB a day until the app is recycled. The change added a scoped PriceDisplayService that subscribes to a singleton PriceFeed's PriceChanged event, and to IOptionsMonitor.OnChange, in its constructor. Why does this leak, how do you prove it with dotnet-counters and dotnet-gcdump, and how do you fix it?

    Observer lifetime mismatch in DI: a scoped subscriber to a singleton subject (event and IOptionsMonitor.OnChange) stays reachable through the delegate invocation list; proving it with dotnet-counters, two dotnet-gcdump snapshots and paths to root; fixing it with IDisposable unsubscription the container calls, moving subscriptions to singletons, lambda pitfalls, weak references, and a WeakReference regression test.

    Mid-Level Debugging Behavioral Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  4. What is the Command pattern? Explain how representing a request as an object enables queuing, retries, undo and auditing, the difference between a GoF command with Execute and a modern command message with a separate handler, and how commands differ from events.

    Command intent and structure (invoker, command, receiver), GoF Execute/Undo commands for undo stacks and macros, modern serialisable command records with ICommandHandler<T>, queuing with Channel<T> or a broker, retries and idempotency keys, audit logs, WPF/MAUI ICommand, and commands vs events.

    Intermediate Theory Behavioral Patterns Β· πŸ”— 3 follow-ups
  5. What is the Mediator pattern, and how does MediatR implement it with request handlers and pipeline behaviours? When is it indirection for nothing, what changed with MediatR's licence, and what alternatives would you consider for a new .NET 10 service?

    GoF Mediator (colleagues talk through a mediator) vs MediatR as an in-process request dispatcher, IRequest/IRequestHandler, INotification, IPipelineBehavior for validation and logging, costs (indirection, navigation, reflection), MediatR's July 2025 move to dual RPL-1.5/commercial licensing under Lucky Penny Software and the Community edition, and alternatives: direct handler injection, decorators, source-generated mediators.

    Mid-Level Theory Behavioral Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  6. What is the Chain of Responsibility pattern? Explain how ASP.NET Core middleware and DelegatingHandler implement it, why the order of handlers matters, how short-circuiting works, and how the classic "handle it or pass it on" chain differs from a pipeline.

    Chain of Responsibility intent and structure, the classic handle-or-pass chain (approval limits) vs the pipeline variant where every handler can act before and after next, ASP.NET Core middleware (RequestDelegate next), DelegatingHandler, short-circuiting, the recommended middleware order, and the costs of long implicit chains.

    Intermediate Theory Behavioral Patterns Β· πŸ”— 3 follow-ups
  7. Model an order lifecycle (Pending, Paid, Shipped, Delivered, Cancelled) as a state machine that rejects invalid transitions such as shipping a cancelled order. Compare a switch expression transition table, the State pattern with state classes, and the Stateless library, and show how you persist the state with EF Core safely under concurrent requests.

    State pattern applied to an order aggregate: (state, trigger) switch-expression transition tables, State classes when behaviour differs per state, the Stateless library (5.20.1) with Permit/PermitIf, external state storage, OnEntry, CanFire and graph export, returning 409 for invalid transitions, persisting the status with EF Core and a rowversion concurrency token, and testing transitions.

    Mid-Level Coding Behavioral Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  8. What is the Visitor pattern and double dispatch? Explain how ExpressionVisitor and Roslyn's syntax walkers use it, why switch expressions with pattern matching are often the modern alternative in C#, what the expression problem is, and when you would still choose a classic visitor.

    Visitor intent, Accept/Visit double dispatch, the expression problem (adding types vs adding operations), ExpressionVisitor in LINQ providers and EF Core, Roslyn CSharpSyntaxWalker and CSharpSyntaxVisitor<T>, pattern-matching switch expressions over record hierarchies as the lighter alternative, exhaustiveness limits in C# 14, costs, and when a classic visitor still wins.

    Senior Theory Behavioral Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  9. What is the Template Method pattern? Explain it using BackgroundService.ExecuteAsync and other framework base classes, the difference between abstract steps and virtual hooks, why a base class with protected virtual methods can become fragile, and when you would use composition instead.

    Template Method intent and structure, non-virtual skeleton with abstract steps and virtual hooks (NVI idiom), framework examples (BackgroundService.ExecuteAsync and its .NET 10 behaviour change, AuthenticationHandler<T>, Collection<T>, DbContext.OnModelCreating, JsonConverter<T>), the fragile base class problem, virtual calls in constructors, and replacing inheritance with strategies or delegates.

    Intermediate Theory Behavioral Patterns Β· πŸ”— 3 follow-ups
  10. What is the Iterator pattern, and how does .NET implement it with IEnumerable<T>/IEnumerator<T>, yield return and IAsyncEnumerable<T>? Why is it useful for hiding a collection's structure, and what deferred-execution gotchas come with it?

    Iterator intent (traverse without exposing structure), IEnumerable<T>/IEnumerator<T> roles, foreach pattern binding, external vs internal iteration, yield return for custom traversals (tree walking), IAsyncEnumerable<T> for paged APIs with await foreach and [EnumeratorCancellation], LINQ over async streams in .NET 10, and gotchas: deferred execution, multiple enumeration, modifying during enumeration and disposal.

    Junior Theory Behavioral Patterns Β· πŸ”— 3 follow-ups
  11. What is the Memento pattern? Explain how to take snapshots for undo without breaking an object's encapsulation, how immutable records and immutable collections make snapshots cheap, how Memento compares with Command-based undo, and how it relates to event sourcing snapshots.

    Memento intent and roles (originator, memento, caretaker), opaque snapshots via a private nested type behind a marker interface, immutable records and with-expressions as free snapshots, structural sharing with ImmutableList<T>, memory costs and capping history, Memento vs Command undo, persisting and versioning snapshots, and snapshots in event sourcing.

    Mid-Level Theory Behavioral Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  12. Implement the Specification pattern for a product catalogue: composable business rules (in stock, price below X, in category) as Expression<Func<T,bool>> that EF Core translates to SQL, with And/Or/Not. Explain why it beats a repository with dozens of GetProductsByXAndY methods, how Ardalis.Specification packages it, and how a spec can accidentally load the whole table.

    Specification pattern in C#: Specification<T> exposing Expression<Func<T,bool>>, And/Or/Not composition with an ExpressionVisitor parameter replacer, in-memory IsSatisfiedBy, translation to SQL by EF Core, repository-method explosion, Ardalis.Specification with criteria, ordering, paging and WithSpecification, the Func<T,bool> vs Expression trap that loads a whole table, and testing translation with ToQueryString and integration tests.

    Mid-Level Coding Behavioral Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  13. What is the Null Object pattern? Explain how NullLogger, Stream.Null, Array.Empty and Task.CompletedTask apply it in .NET, how it compares with nullable reference types and null checks, and when a null object hides real errors instead of preventing them.

    Null Object intent (a do-nothing implementation instead of null), framework examples (NullLogger<T>.Instance, NullLoggerFactory, Stream.Null, TextWriter.Null, Array.Empty<T>, Enumerable.Empty<T>, Task.CompletedTask, CancellationToken.None), returning empty collections, optional dependencies in DI, comparison with nullable reference types and the Maybe/Result approach, and when a null object masks failures.

    Junior Theory Behavioral Patterns Β· πŸ”— 3 follow-ups
  14. Code review: an OrderProcessor has a long if/else chain on order type and region for pricing, sets Status strings directly, subscribes to a static InventoryChanged event in its constructor and never unsubscribes, and publishes events through a hand-written mediator that resolves handlers from the root IServiceProvider and calls them with reflection. Which behavioural patterns would you apply, which would be overkill, and how would you rewrite it?

    Senior code review of an order processor: static event leak from a scoped service, a home-made mediator resolving scoped handlers from the root provider and invoking async handlers via reflection (lost exceptions), cancelled orders processed through direct status writes, events lost without an outbox, pricing if/else chains; ranking by severity, choosing Strategy and a switch-table State, rejecting overkill patterns, the rewrite, and how to close the review.

    Senior CodeReview Behavioral Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  15. What is the Repository pattern? Explain its intent, how it differs from a DAO or a table gateway, why a generic IRepository<T> with GetAll, Update and Save over EF Core is often an anti-pattern, and what a good repository interface looks like in a .NET 10 service.

    Repository pattern in .NET: intent (a collection-like abstraction over persistence for an aggregate root), repository vs DAO/table gateway, why a generic IRepository<T> over EF Core leaks IQueryable, breaks the unit of work with per-repository Save, encourages Update() on detached graphs and repositories for child entities, and what a narrow, aggregate-specific repository interface looks like with DI registration.

    Intermediate Theory Enterprise Patterns Β· πŸ”— 5 follow-ups
  16. Your team is starting a new .NET 10 service on EF Core 10 and is split on whether to wrap DbContext in repositories. How do you decide? Cover testability (mocks, the in-memory provider, Testcontainers), aggregate boundaries, leaking IQueryable, ExecuteUpdate/ExecuteDelete, and the situations where your answer changes.

    Architecture decision on wrapping EF Core in repositories: testing with mocks vs EF in-memory/SQLite vs Testcontainers SQL Server, aggregate repositories for the write side vs direct DbContext projections for reads, leaky IQueryable, EF Core 10 ExecuteUpdate/ExecuteDelete (non-expression setter lambda) bypassing the change tracker, multiple persistence stores, team skill and when the decision flips, recorded as an ADR.

    Senior Architecture Enterprise Patterns Β· πŸ”— 5 follow-ups Β· πŸ›  1 real-world
  17. What is the Unit of Work pattern? Explain how EF Core's DbContext already implements it with the change tracker and SaveChanges, when you need an explicit transaction (BeginTransactionAsync, execution strategies with retries), how ExecuteUpdate/ExecuteDelete fit in, and why all repositories in a request should share one DbContext.

    Unit of Work in .NET: tracking changes and committing them as one transaction, EF Core's change tracker and SaveChangesAsync as the built-in UoW (implicit transaction, identity map), explicit transactions with BeginTransactionAsync for multiple SaveChanges or ExecuteUpdate/ExecuteDelete/raw SQL, wrapping them in CreateExecutionStrategy().ExecuteAsync when EnableRetryOnFailure is on, TransactionScope caveats, and sharing one scoped DbContext across repositories.

    Intermediate Theory Enterprise Patterns Β· πŸ”— 2 follow-ups
  18. What is the difference between a service layer, an application service and a domain service? Explain what goes where in a DDD-style .NET application, how a fat service layer leads to an anaemic domain model, and how you keep business rules out of controllers and handlers.

    Service layer (Fowler) vs application service vs domain service (Evans/DDD): responsibilities (orchestration, transactions, authorisation and mapping vs stateless domain logic spanning aggregates), what belongs in entities, how 'god' service layers create an anaemic domain model, thin controllers/minimal API endpoints, and a funds-transfer example in .NET 10.

    Intermediate Theory Enterprise Patterns Β· πŸ”— 4 follow-ups
  19. What is a Data Transfer Object (DTO)? Explain where the pattern comes from, why you shouldn't return or bind EF Core entities directly in an ASP.NET Core API (over-posting, leaking fields, versioning, serialisation cycles), why C# records make good DTOs, and where DTOs are and aren't needed.

    DTO pattern: Fowler's origin (batching data across a process boundary), a data-only contract with no behaviour, why exposing EF Core entities in APIs is risky (over-posting/mass assignment, leaking sensitive fields under the Privacy Act, schema changes breaking clients, JSON object cycles), separate request and response DTOs, records as immutable DTOs, and when not to add DTOs (inside one layer).

    Junior Theory Enterprise Patterns Β· πŸ”— 3 follow-ups
  20. How should you map between EF Core entities and DTOs in .NET 10? Compare hand-written mapping, AutoMapper and Mapperly (a source generator), including their current licences, run-time cost and failure modes, and explain why projecting with Select (or ProjectTo) in the query often beats mapping entities after loading them.

    Mapper pattern in .NET 10: hand-written mapping (extension methods, constructors), AutoMapper (reflection/expression-compiled, ProjectTo, AssertConfigurationIsValid; dual RPL-1.5/commercial from v15, July 2025; free Community edition under US$5M revenue; 14.x last MIT with an unpatched advisory), Mapperly (Apache 2.0 source generator, build-time diagnostics, IQueryable projections), mapping after loading vs Select projection in EF Core (over-fetching, tracking, lazy-loading N+1), and testing mappings.

    Mid-Level Theory Enterprise Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me