📁 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. What are design patterns? Explain the GoF split into creational, structural and behavioural patterns, give a .NET example of each, and tell me when using a pattern makes code worse.

    What design patterns are, the three GoF categories with .NET framework examples (DI lifetimes, IHttpClientFactory, StringBuilder, Stream wrappers, DelegatingHandler, IEnumerable, middleware), and when a pattern is ceremony.

    Beginner Theory Creational Patterns Β· πŸ”— 2 follow-ups
  2. How do you implement a thread-safe Singleton in C#? Compare a static readonly field, Lazy<T> and double-checked locking, and explain why in an ASP.NET Core app you would normally register a singleton in DI instead.

    Singleton intent, three thread-safe C# implementations (static readonly with type initialiser guarantees, Lazy<T> with ExecutionAndPublication, double-checked locking with volatile), their pitfalls, and why the DI singleton lifetime replaces the hand-rolled pattern.

    Junior Theory Creational Patterns Β· πŸ”— 3 follow-ups
  3. Your ASP.NET Core API sometimes returns another user's data, and after a refactor startup fails with "Cannot consume scoped service 'AppDbContext' from singleton". What is a captive dependency, how do you diagnose and fix it, and how do ValidateScopes and ValidateOnBuild help?

    Captive dependencies (a singleton holding a scoped or transient service), the data-leak and thread-safety symptoms, ValidateScopes and ValidateOnBuild, and fixes with IServiceScopeFactory, lifetime changes and IHttpClientFactory.

    Mid-Level Debugging Creational Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  4. What is the difference between a simple factory, the Factory Method pattern and the Abstract Factory pattern? Give a .NET framework example of each and explain when DI makes a hand-written factory unnecessary.

    Simple factory vs GoF Factory Method (subclass decides, DbConnection.CreateCommand) vs Abstract Factory (families of related objects, DbProviderFactory, DbDataSource), IHttpClientFactory and ILoggerFactory, and when DI factory delegates replace them.

    Intermediate Theory Creational Patterns Β· πŸ”— 3 follow-ups
  5. You have several payment gateways (Stripe, PayPal, a bank API) and the right one depends on the order. Show how you would select the implementation at run time in ASP.NET Core using DI: factory delegates, keyed services with [FromKeyedServices], and an IEnumerable-based resolver. How do you avoid the service locator anti-pattern?

    Run-time implementation selection in .NET 10 DI: keyed services (AddKeyedScoped, [FromKeyedServices], GetRequiredKeyedService), Func factory delegates, an IEnumerable-to-FrozenDictionary resolver, unknown-key handling, testing, and keeping IServiceProvider at the composition root.

    Mid-Level Coding Creational Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  6. What is the Builder pattern? Explain fluent builders, how WebApplicationBuilder and HostApplicationBuilder use it, test data builders, and when C# required and init properties with an object initialiser are enough instead.

    GoF Builder vs fluent builder, framework builders (StringBuilder, UriBuilder, SqlConnectionStringBuilder, WebApplicationBuilder, HostApplicationBuilder, DbContextOptionsBuilder, ResiliencePipelineBuilder), test data builders, validation in Build(), and when required/init initialisers replace a builder.

    Intermediate Theory Creational Patterns Β· πŸ”— 2 follow-ups
  7. What is the Prototype pattern? Explain shallow versus deep copies, how MemberwiseClone works, why ICloneable is discouraged, and why a record's with expression can still surprise you.

    Prototype intent, shallow vs deep copy, MemberwiseClone semantics, ICloneable's ambiguity, records and with (shallow copy constructor), deep-copy options, JsonSerializerOptions and HttpRequestMessage cloning, and EF Core PropertyValues.Clone.

    Mid-Level Theory Creational Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  8. When does the Object Pool pattern help in .NET, and when does it make things slower? Explain ObjectPool<T>, ArrayPool<T>, DbContext pooling and connection pooling, the bugs that come from resetting pooled objects badly, and how you would prove a pool is worth it.

    Object Pool in .NET 10: Microsoft.Extensions.ObjectPool (policies, IResettable, MaximumRetained), ArrayPool<T>.Shared, AddDbContextPool, ADO.NET connection pooling, reset and use-after-return bugs, why pooling can be slower than gen0 allocation, and measuring with BenchmarkDotNet and dotnet-counters.

    Senior Theory Creational Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  9. Code review: a CurrencyService exposes a hand-rolled static Instance, caches rates in a plain Dictionary, creates new HttpClient() and new AppDbContext() itself, calls .Result on async code, and picks a rate provider with a switch on a config string. What is wrong, in order of severity, and how would you rewrite it with DI?

    Code review of creational anti-patterns: racy static singleton, unsynchronised Dictionary, HttpClient per call, DbContext held by a singleton, sync-over-async, switch factory with silent fallback and hard-coded secret; rewrite with DI lifetimes, typed HttpClient, HybridCache, keyed or options-driven provider selection.

    Senior CodeReview Creational Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  10. What is the Adapter pattern? Show how you would wrap a third-party payment SDK behind your own interface, explain object versus class adapters, and say what belongs inside the adapter and what does not.

    Adapter intent, object vs class adapter, wrapping a vendor SDK (Stripe.net) behind a domain interface, translating units, types and exceptions, .NET examples (StreamReader, TaskCompletionSource, Serilog's ILoggerProvider), and keeping business logic out of adapters.

    Junior Theory Structural Patterns Β· πŸ”— 2 follow-ups
  11. What is the Decorator pattern? Explain how it adds behaviour such as caching, logging or retry without changing the original class, where .NET uses it (Stream wrappers, DelegatingHandler), and how you register decorators with the built-in DI container.

    Decorator intent and structure, composition-based stacking, .NET examples (BufferedStream, GZipStream, CryptoStream, DelegatingHandler pipelines), registering decorators with factory delegates, keyed services or Scrutor, ordering, and decorators vs inheritance, middleware and AOP.

    Intermediate Theory Structural Patterns Β· πŸ”— 3 follow-ups
  12. Write a caching decorator for IProductRepository using HybridCache in .NET 10. Register it with the built-in container, then with Scrutor, and explain how you handle invalidation, cache keys, stampedes and the risk of caching errors or other users' data.

    Coding a HybridCache caching decorator: GetOrCreateAsync with keys and TTLs, stampede protection, invalidation on writes (RemoveAsync, tags), not caching nulls or failures by accident, tenant-aware keys, immutable cached types, registration via factory delegate, keyed services and Scrutor, and tests.

    Mid-Level Coding Structural Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  13. What is the Facade pattern? Give examples from .NET and from a typical business application, and explain how a good facade differs from a 'god service' that does everything.

    Facade intent (a simple entry point over a subsystem), .NET examples (File.ReadAllTextAsync, HttpClient, JsonSerializer, DbContext), an order-checkout facade, facade vs god service vs application service, and keeping facades thin.

    Intermediate Theory Structural Patterns Β· πŸ”— 2 follow-ups
  14. What is the Proxy pattern? Explain virtual, remote and protection proxies, and how EF Core lazy-loading proxies, DispatchProxy and Castle DynamicProxy implement it. What are the risks of proxies you can't see in the code?

    Proxy intent and kinds (virtual, remote, protection, smart reference), EF Core lazy-loading proxies (virtual navigations, Castle, N+1, disposed-context errors), DispatchProxy for interfaces (and its AOT limits), Castle DynamicProxy interceptors, generated HTTP/gRPC clients, and the cost of invisible behaviour.

    Mid-Level Theory Structural Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  15. What is the Composite pattern? Show how you would model a tree of permissions, pricing rules or menu items so that clients treat single items and groups the same way, where .NET uses it, and how you guard against deep recursion and cycles.

    Composite intent (part-whole trees with a uniform interface), leaf vs composite, a permission-group or rule tree in C#, .NET examples (CompositeFileProvider, CompositeChangeToken, expression trees), recursion depth and StackOverflowException, cycle detection, and storing hierarchies (recursive CTE, hierarchyid).

    Mid-Level Theory Structural Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  16. What is the Bridge pattern, and what problem does it solve? Use a notifications example (message types × channels) and explain how ILogger/ILoggerProvider and HttpClient/HttpMessageHandler are bridges in .NET. How is Bridge different from Adapter and Strategy?

    Bridge intent (separate an abstraction from its implementation so both vary independently), avoiding M×N class explosions, notification types × channels in C#, ILogger over ILoggerProvider and HttpClient over HttpMessageHandler, and Bridge vs Adapter vs Strategy.

    Mid-Level Theory Structural Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  17. Adapter, Decorator, Proxy and Facade all wrap something. How do you tell them apart? Compare their intent, interface and typical .NET examples, and explain why the distinction matters in a real codebase.

    A comparison of the four wrapper patterns: Adapter (converts an interface), Decorator (same interface, adds behaviour), Proxy (same interface, controls access and lifecycle), Facade (new simpler interface over many classes), with .NET examples, a decision guide, and why mislabelling leads to misplaced logic such as duplicate retries.

    Mid-Level Theory Structural Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  18. What is the Flyweight pattern? Explain intrinsic versus extrinsic state, how .NET uses flyweights (string interning, cached instances, SearchValues, frozen collections), when deduplicating objects actually saves memory, and how you would prove the saving with dotnet-gcdump.

    Flyweight intent (share immutable intrinsic state, pass extrinsic state in), string literal interning and string.Intern's process-lifetime cost, custom string pools, cached instances (Task.CompletedTask, Array.Empty, CultureInfo), SearchValues and FrozenDictionary as precomputed shared state, and measuring with dotnet-gcdump and dotnet-counters.

    Senior Theory Structural Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  19. After a refactor, your API starts caching error responses for an hour, some outgoing calls are retried far more often than configured, and every log line appears twice. You suspect the order of decorators and HttpClient handlers. How do you diagnose and fix it?

    Debugging decorator and DelegatingHandler ordering: fallbacks cached by a cache decorator, timeouts and retries layered in the wrong order or twice (custom handler plus AddStandardResilienceHandler), duplicate logging from double registration; inspecting IServiceCollection descriptors, the resolved decorator chain, handler order, and OpenTelemetry span nesting; tests that lock the order.

    Senior Debugging Structural Patterns Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  20. 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

🌐 Sangam's Webring

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