📁 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.

Behavioral Patterns

Strategy, Observer, Command, Mediator, Chain of Responsibility, State, Visitor, Template Method, Iterator, Memento, Specification and Null Object in modern C#.

  1. What is the Strategy pattern? Explain how it replaces a switch on a type or mode, how you register several strategies in DI and pick one at run time (IEnumerable<IStrategy> or keyed services), and when a plain delegate is a better, lighter-weight strategy.

    Strategy intent and structure, replacing growing switch statements with interchangeable algorithms, .NET examples (IComparer<T>, IEqualityComparer<T>, StringComparer, JsonNamingPolicy), selecting strategies via IEnumerable<T>, a dictionary or keyed services, delegates as one-method strategies, and when a switch is still clearer.

    Junior Theory Behavioral Patterns Β· πŸ”— 4 follow-ups
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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

🌐 Sangam's Webring

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