PrepStack › Backend › C# & ASP.NET Core

C# & ASP.NET Core interview cheat sheet

CLR, type system, LINQ, async/await, DI, middleware and EF Core

C# interviews usually start with the runtime and type system: value vs reference types, boxing, records, the GC and IDisposable. Then they move to LINQ and async/await, and finish with ASP.NET Core: the middleware pipeline, DI lifetimes, configuration, auth and EF Core performance. Read the 15-minute revision first, then switch to Quiz mode and answer out loud. Version facts match .NET 10 (LTS, C# 14) and .NET 11 (STS, C# 15).

15-minute revision

  1. .NET (formerly .NET Core) is cross-platform, open source and ships yearly each November. Even versions are LTS (3 years), odd ones are STS (2 years). .NET 10 is the current LTS. .NET Framework 4.8.x is Windows-only and in maintenance.
  2. C# compiles to IL. The CLR loads it and the JIT turns it into machine code at runtime (tiered: quick code first, optimized later). Native AOT compiles ahead of time instead.
  3. Value types (struct, enum, int, bool) hold their data and are copied on assignment. Reference types (class, string, arrays, delegates) hold a reference to a heap object.
  4. Boxing copies a value type into a new heap object when it is treated as object or an interface. Unboxing casts it back and copies again. Generics avoid it.
  5. record gives value-based equality, a readable ToString and with copies. record class is a reference type; record struct is a value type.
  6. string is immutable: every change makes a new string. Build strings in loops with StringBuilder.
  7. ref = pass by reference, must be initialized first. out = method must assign it. in = read-only reference. All three pass the variable, not a copy.
  8. Nullable reference types (string?) are compile-time warnings only. Nullable<T> (int?) is a real runtime wrapper for value types.
  9. Func<> returns a value, Action<> returns void. An event is a delegate that outsiders can only += / -=, not invoke or overwrite.
  10. LINQ is deferred: nothing runs until you enumerate. IEnumerable<T> runs in memory with delegates; IQueryable<T> builds an expression tree that a provider (EF Core) turns into SQL.
  11. await frees the thread while waiting. Never block on async code with .Result / .Wait(). Use ConfigureAwait(false) in library code. Avoid async void except event handlers.
  12. GC is generational (Gen 0, 1, 2) plus the LOH for objects of 85,000 bytes or more. The GC frees memory only; release files, sockets and connections with IDisposable + using.
  13. Use throw; to rethrow. throw ex; resets the stack trace. Catch specific exceptions and use when filters.
  14. Middleware runs in registration order on the way in and in reverse on the way out. UseAuthentication must come before UseAuthorization.
  15. DI lifetimes: Singleton (one per app), Scoped (one per request), Transient (new every time). Never inject a scoped service into a singleton (captive dependency).
  16. EF Core: DbContext is scoped and not thread-safe. Use AsNoTracking() for read-only queries, Include to avoid N+1, and project with Select to fetch only needed columns.

Platform & type system

.NET platform, CLR, IL & JIT

C# compiles to IL, and the CLR runs it with a JIT compiler, a garbage collector and a common type system.

  • .NET (5 and later, formerly .NET Core) is cross-platform and open source. .NET Framework (last version 4.8.1) is Windows-only and gets only security fixes. New work targets .NET.
  • Release rhythm: a major version every November. LTS (even numbers) gets 3 years of support, STS (odd numbers) gets 2 years. .NET 10 (Nov 2025) is LTS; .NET 11 (Nov 2026) is STS.
  • CLR (Common Language Runtime) loads assemblies, verifies and JIT-compiles IL, manages memory with the GC, handles exceptions, threads and type safety.
  • IL / CIL is the CPU-independent bytecode stored in .dll files, together with metadata that describes every type and member.
  • CTS (Common Type System) defines how types work across all .NET languages. CLS (Common Language Specification) is the smaller subset a library should expose so every .NET language can use it.
  • JIT compiles each method on its first call. Tiered compilation first produces fast-to-make code, then recompiles hot methods with full optimization, guided by Dynamic PGO (on by default since .NET 8).
  • ReadyToRun ships precompiled code to speed startup but keeps IL. Native AOT produces a single native binary with no JIT: fast startup and small memory, but limited reflection and no runtime code generation.

Interview questions

  • Difference between .NET and .NET Framework?
  • Explain CLR, CTS, CLS and IL.
  • What is JIT compilation and what is tiered compilation?

Value vs reference types, boxing & ref/out/in

Value types copy their data; reference types copy a pointer. Boxing wraps a value in a heap object; ref/out/in pass the variable itself.

  • Value types: int, double, bool, char, decimal, DateTime, enum, any struct. A variable holds the data, so assignment copies it.
  • Reference types: class, string, arrays, delegates, object, interfaces. A variable holds a reference; two variables can point to the same object.
  • Stack vs heap is an implementation detail: value-type locals usually live on the stack, but a value type that is a field of a class lives inside that object on the heap. Reference-type objects always live on the heap.
  • Boxing happens when a value type is converted to object or an interface it implements: a new heap object is allocated and the value is copied in. Unboxing is an explicit cast back to the exact type.
  • By default C# passes arguments by value (for reference types, the reference is copied). ref, out and in pass a reference to the caller's variable.
  • ref: caller must initialize, method may read and write. out: method must assign before returning (used by TryParse). in: read-only reference, useful for large structs. params accepts a variable number of arguments.

Interview questions

  • Difference between value types and reference types?
  • Are value types always stored on the stack?
  • What are boxing and unboxing, and why do they matter?
  • Difference between ref and out?

struct vs class vs record

Use a class for identity and behaviour, a small readonly struct for tiny values, and a record for immutable data with value equality.

  • class: reference type, reference equality by default, supports inheritance. The default choice for most types.
  • struct: value type, copied on assignment, no inheritance (can implement interfaces). Good for small (around 16 bytes or less), immutable values like Point or Money.
  • record (C# 9) is a class with compiler-generated value equality, ToString, deconstruction and with expressions. record struct (C# 10) does the same for value types.
  • Positional records like record Person(string Name, int Age) create a primary constructor and init-only properties (for record class and readonly record struct).
  • A with expression makes a shallow copy with some properties changed. Nested reference objects are shared, not cloned.
  • C# 12 added primary constructors for all classes and structs. Unlike records, these parameters do not become public properties.

Interview questions

  • Difference between struct and class?
  • What does a record give you over a class?
  • Is a record immutable?
  • Record class vs record struct?

Strings, immutability & StringBuilder

Strings never change; every edit creates a new one. Use StringBuilder for many appends and ordinal comparisons for identifiers.

  • string is a reference type with value semantics: == and Equals compare characters, not references.
  • Strings are immutable. Replace, ToUpper and + return new strings. This makes them thread-safe and safe as dictionary keys.
  • Concatenating in a loop is O(n²) because each step copies everything so far. StringBuilder keeps a growable buffer and builds once at ToString().
  • For a few pieces, +, interpolation $"...", string.Concat or string.Join are fine and often faster than a StringBuilder.
  • The runtime interns string literals: identical literals share one instance. Strings built at runtime are not interned unless you call string.Intern.
  • Comparisons: use StringComparison.Ordinal / OrdinalIgnoreCase for keys, paths and protocol values; culture-aware comparison only for text shown to users.

Interview questions

  • Why are strings immutable in .NET?
  • When should you use StringBuilder?
  • Difference between == and Equals for strings?

Nullable value types & nullable reference types

int? is a runtime wrapper; string? is a compile-time annotation that makes the compiler warn about possible nulls.

  • Nullable<T> (int?) wraps a value type with HasValue and Value. GetValueOrDefault() avoids exceptions.
  • Nullable reference types (NRT), enabled with <Nullable>enable</Nullable> (on in new templates), make string mean “never null” and string? mean “may be null”.
  • NRT is static analysis only: no runtime checks, and the compiled type is still string. Public APIs should still validate with ArgumentNullException.ThrowIfNull.
  • Operators: ?. (null-conditional access), ?? (fallback), ??= (assign if null), ! (null-forgiving: “trust me”, silences the warning).
  • C# 14 added null-conditional assignment: customer?.Order = order; assigns only if customer is not null.
  • Attributes such as [NotNullWhen(true)], [MaybeNull] and [MemberNotNull] teach the compiler about your own null checks.

Interview questions

  • Difference between int? and string??
  • What does the ! operator do?
  • How would you migrate a large codebase to nullable reference types?

Garbage collection, IDisposable & using

The generational GC frees managed memory automatically; unmanaged resources must be released deterministically with Dispose.

  • The GC is generational: new objects go to Gen 0. Survivors are promoted to Gen 1, then Gen 2. Most objects die young, so Gen 0 collections are cheap and frequent.
  • Objects of 85,000 bytes or more go to the Large Object Heap (logically Gen 2). It is not compacted by default, so it can fragment. Pool big buffers with ArrayPool<T>.
  • A collection marks reachable objects from roots (stack variables, statics, GC handles), sweeps the rest, and compacts to remove gaps. Threads pause during parts of this.
  • Workstation GC suits desktop apps; Server GC (default for ASP.NET Core) uses one heap per core for throughput. Background GC runs Gen 2 work concurrently.
  • IDisposable.Dispose() releases unmanaged or expensive resources (files, sockets, DB connections) now. using calls it automatically, even when an exception is thrown.
  • A finalizer (~Type()) is a safety net for unmanaged handles. It delays collection by at least one GC cycle. Prefer SafeHandle; call GC.SuppressFinalize(this) in Dispose.
  • IAsyncDisposable with await using disposes asynchronously (for example, flushing a stream or closing a DB connection).

Interview questions

  • How does garbage collection work in .NET?
  • Difference between Dispose and Finalize?
  • If .NET has a GC, why do we need IDisposable?

Core C# language

Properties, interfaces vs abstract classes

Properties wrap fields with accessors; interfaces define contracts, abstract classes share code and state.

  • A property is a pair of get/set (or init) methods that looks like a field. Auto-properties generate the backing field for you.
  • init (C# 9) allows setting only during object creation. required (C# 11) forces callers to set the member in the object initializer.
  • C# 14 added the field keyword: use the compiler's backing field inside an accessor without declaring your own field.
  • An interface is a contract: a class can implement many. Since C# 8 interfaces can have default method implementations, and since C# 11 static abstract members (used by generic math).
  • An abstract class can have fields, constructors, and abstract plus concrete members, but a class can inherit only one base class.
  • virtual allows overriding, override replaces it, sealed stops further overriding, and new hides a base member (avoid; it breaks polymorphism).

Interview questions

  • Difference between an interface and an abstract class?
  • Field vs property?
  • What is the difference between override and new?

Delegates, events, Func/Action & lambdas

A delegate is a type-safe reference to a method; events restrict a delegate so only the owner can raise it.

  • A delegate is a type that represents a method signature. An instance holds one or more methods (multicast) and calls them in order.
  • Built-in generic delegates: Func<T, TResult> (returns a value), Action<T> (returns void), Predicate<T> (returns bool). Prefer them over custom delegate types.
  • A lambda (x => x * 2) creates a delegate or, when assigned to Expression<Func<...>>, an expression tree that can be inspected (how EF Core builds SQL).
  • Lambdas capture variables, not values. The captured variable moves to a compiler-generated class on the heap (a closure).
  • An event wraps a delegate field: outside code can only += and -=. Only the declaring class can raise it. Standard signature: EventHandler<TEventArgs>.
  • static lambdas (C# 9) cannot capture anything, which avoids accidental allocations.

Interview questions

  • What is a delegate?
  • Difference between a delegate and an event?
  • What is a closure and what is the loop-capture trap?

Generics, constraints & extension methods

Generics give type-safe reusable code without boxing; constraints say what T can do; extension methods add methods to existing types.

  • Generics are reified in .NET: List<int> and List<string> are real distinct types at runtime. Value-type instantiations get specialized code, so no boxing.
  • Constraints: where T : class, struct, notnull, unmanaged, new(), a base class, an interface, or allows ref struct (C# 13).
  • Variance on interfaces and delegates: out T is covariant (IEnumerable<string> to IEnumerable<object>), in T is contravariant (Action<object> to Action<string>).
  • Extension methods are static methods in a static class whose first parameter has this. They are resolved at compile time; instance methods win on name clashes.
  • C# 14 extension members use an extension (Type receiver) { ... } block and also allow extension properties and static members. C# 15 adds extension indexers.
  • LINQ is entirely extension methods on IEnumerable<T> and IQueryable<T>.

Interview questions

  • What are generic constraints? Give examples.
  • Explain covariance and contravariance.
  • How do extension methods work?

LINQ: deferred execution, IEnumerable vs IQueryable

Most LINQ operators build a pipeline that runs only when enumerated; IQueryable translates the pipeline into another language like SQL.

  • Deferred execution: Where, Select, OrderBy, Skip and friends return a query object. Work happens when you foreach, or call ToList, Count, First, Sum, etc.
  • Each enumeration re-runs the query. Multiple enumeration of a database query means multiple round trips. Materialize once with ToList() when you need it twice.
  • Streaming operators (Where, Select) yield items one by one. Buffering operators (OrderBy, GroupBy, Reverse) must read all input first.
  • IEnumerable<T> runs in memory using delegates. IQueryable<T> holds an expression tree that a provider translates (EF Core to SQL), so filtering happens on the server.
  • Calling AsEnumerable() or ToList() too early pulls the whole table into memory and filters there.
  • Know the pairs: First (throws if empty) vs FirstOrDefault; Single (throws if not exactly one); Any() vs Count() > 0; Select vs SelectMany (flattens).

Interview questions

  • What is deferred execution in LINQ?
  • Difference between IEnumerable and IQueryable?
  • First vs FirstOrDefault vs Single?

Exceptions & error handling

Throw for exceptional cases, catch only what you can handle, rethrow with throw;, and let a global handler turn the rest into ProblemDetails.

  • All exceptions derive from System.Exception. Common ones: ArgumentNullException, InvalidOperationException, KeyNotFoundException, NotSupportedException, OperationCanceledException.
  • finally always runs after try/catch (except when the process dies, for example from a StackOverflowException).
  • throw; rethrows and keeps the original stack trace. throw ex; resets it to the current line. To add context, wrap it: throw new XException("msg", ex).
  • Exception filters (catch (HttpRequestException e) when (e.StatusCode == HttpStatusCode.NotFound)) decide before the stack unwinds and do not lose the trace.
  • Order catch blocks from most specific to most general. Avoid empty catch {} and catching Exception except at app boundaries.
  • Exceptions are expensive. Use TryParse / TryGetValue or result types for expected failures like invalid input.

Interview questions

  • Difference between throw and throw ex?
  • What are exception filters for?
  • How do you handle errors globally in an ASP.NET Core API?

Pattern matching & modern C# (12–15)

Patterns test shape and values in is and switch expressions; recent versions added collection expressions, primary constructors, field, extension members and unions.

  • Pattern kinds: type (o is string s), constant (is null), relational (> 0), logical (and, or, not), property ({ Age: > 18 }), positional ((0, 0)), list ([1, .., 9], C# 11).
  • A switch expression returns a value, and the compiler warns when it is not exhaustive.
  • C# 12 (.NET 8): primary constructors for classes, collection expressions (int[] a = [1, 2, 3];, spread ..), default lambda parameters, alias any type.
  • C# 13 (.NET 9): params collections (params ReadOnlySpan<T>), the new System.Threading.Lock type, \e escape, partial properties.
  • C# 14 (.NET 10 LTS): extension members, the field keyword, null-conditional assignment (a?.B = c), nameof on unbound generics, more implicit Span conversions.
  • C# 15 (.NET 11): union types (public union Pet(Cat, Dog);), closed class hierarchies for exhaustive switches, collection expression arguments ([with(capacity: 10), ..items]), labeled break/continue.

Interview questions

  • What is pattern matching in C#?
  • What are the latest C# and .NET versions?
  • Name a few C# features from the last few versions you actually use.

Async & concurrency

async/await, Task, ConfigureAwait & deadlocks

await releases the thread until the awaited work finishes, then resumes the rest of the method; blocking on async code can deadlock or starve the thread pool.

  • A Task represents an operation that will complete later; Task<T> also carries a result. async lets a method use await; it does not create a thread by itself.
  • For I/O-bound work (HTTP, DB, files) await uses no thread while waiting. For CPU-bound work, use Task.Run to move it to the thread pool (in UI apps, not in ASP.NET request code).
  • After await, the continuation resumes on the captured SynchronizationContext (UI thread, legacy ASP.NET) if there is one; otherwise on a thread-pool thread. ASP.NET Core has no SynchronizationContext.
  • ConfigureAwait(false) says “do not resume on the captured context”. Use it in library code. It is unnecessary in ASP.NET Core app code but harmless.
  • Deadlock: on a UI thread, GetAsync().Result blocks the thread while the continuation waits for that same thread. In ASP.NET Core, blocking causes thread-pool starvation instead.
  • async void cannot be awaited and its exceptions crash the process; use it only for event handlers. Return Task otherwise.
  • ValueTask<T> avoids an allocation when results are often synchronous, but must be awaited only once. Pass a CancellationToken through every async call.

Interview questions

  • What actually happens at an await?
  • Why can .Result deadlock?
  • Is ConfigureAwait(false) needed in ASP.NET Core?
  • Difference between Task and Thread?

ASP.NET Core

Hosting & the middleware pipeline

Each request flows through an ordered chain of middleware; each piece can act, call next, or short-circuit.

  • WebApplication.CreateBuilder(args) sets up the host: Kestrel web server, configuration, logging and the DI container. builder.Build() creates the app; app.Run() starts it.
  • Middleware is a component with access to HttpContext and a next delegate. app.Use(...) adds one that can call next; app.Run(...) is terminal; app.Map("/path", ...) branches.
  • Order is everything: middleware runs top to bottom for the request and bottom to top for the response.
  • Typical order: exception handler → HSTS → HTTPS redirection → static files → routing → CORS → authentication → authorization → custom middleware → endpoints.
  • Short-circuiting: static files, CORS preflight and auth failures can return a response without calling next.
  • Write class-based middleware with an InvokeAsync(HttpContext ctx) method. Constructor-injected services are effectively singletons; inject scoped services as InvokeAsync parameters.

Interview questions

  • What is middleware in ASP.NET Core?
  • Difference between Use, Run and Map?
  • Why does middleware order matter? Give an example.
  • Middleware vs filters?

Dependency injection & service lifetimes

The built-in container creates services as singleton, scoped (per request) or transient; a longer-lived service must never hold a shorter-lived one.

  • Register in builder.Services; consume through constructor injection (or parameters in minimal API handlers and InvokeAsync).
  • Singleton: one instance for the app's life; must be thread-safe. Scoped: one per request (DI scope). Transient: a new instance every time it is resolved.
  • Captive dependency: a singleton that takes a scoped service keeps it alive forever (for example, a DbContext shared across all requests). In Development, scope validation throws at startup or resolve time for this.
  • To use scoped services from a singleton or BackgroundService, inject IServiceScopeFactory and create a scope per unit of work.
  • The container disposes the IDisposable services it created at the end of their scope (or app shutdown for singletons).
  • Keyed services (.NET 8): AddKeyedSingleton<ICache, RedisCache>("redis") and [FromKeyedServices("redis")] to pick an implementation by key.

Interview questions

  • Explain singleton, scoped and transient.
  • What is a captive dependency and how do you fix it?
  • How do you use a DbContext inside a hosted service?
  • Why use DI at all?

Minimal APIs vs controllers, routing, binding, validation & filters

Both styles share routing and binding; minimal APIs are lighter, controllers add conventions and the MVC filter pipeline.

  • Minimal APIs map handlers directly (app.MapGet(...)), with groups via MapGroup. Less ceremony, faster startup, Native AOT friendly.
  • Controllers ([ApiController] + ControllerBase) group actions in classes and give automatic 400 responses on invalid models, binding source inference and the full filter pipeline.
  • Routing matches URL and HTTP method to an endpoint. Route templates support constraints: {id:int}, {slug:alpha}, optional {page?}, defaults.
  • Model binding sources: route, query, header, body (JSON), form, and DI services. Attributes: [FromRoute], [FromQuery], [FromBody], [FromHeader], [FromServices], [AsParameters].
  • Validation: DataAnnotations ([Required], [Range], [EmailAddress]) or FluentValidation. Controllers check ModelState automatically; minimal APIs get built-in validation in .NET 10 with builder.Services.AddValidation().
  • Filters (MVC) run in order: authorization → resource → model binding → action → exception → result. Minimal APIs use endpoint filters (AddEndpointFilter).
  • Return types: Results.Ok(...) / TypedResults.NotFound() in minimal APIs; ActionResult<T> / IActionResult in controllers.

Interview questions

  • Minimal APIs or controllers: which would you choose?
  • How does model binding decide where a parameter comes from?
  • What filter types exist and in what order do they run?
  • How do you validate input in ASP.NET Core?

Configuration, options pattern & logging

Configuration merges many sources by priority; bind sections to typed options classes; log with structured message templates through ILogger<T>.

  • Default sources, later wins: appsettings.json → appsettings.{Environment}.json → user secrets (Development) → environment variables → command-line args.
  • Keys are hierarchical with : (Jwt:Issuer). In environment variables use a double underscore: Jwt__Issuer. The environment comes from ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT).
  • Options pattern: bind a section to a class with services.AddOptions<T>().Bind(...) or Configure<T>(...), then inject IOptions<T>, IOptionsSnapshot<T> or IOptionsMonitor<T>.
  • Validate options at startup with .ValidateDataAnnotations().ValidateOnStart() so bad config fails fast.
  • Never put secrets in appsettings.json. Use user secrets locally and Key Vault / environment variables / a secret store in production.
  • Logging: inject ILogger<T>. Use message templates ("Order {OrderId} paid") not interpolation, so providers like Serilog or OpenTelemetry store OrderId as a field. Levels: Trace, Debug, Information, Warning, Error, Critical.
  • For hot paths, the [LoggerMessage] source generator creates fast, allocation-free logging methods.

Interview questions

  • How does configuration precedence work?
  • IOptions vs IOptionsSnapshot vs IOptionsMonitor?
  • Why use message templates instead of string interpolation in logs?

Authentication & authorization (JWT, policies)

Authentication works out who the caller is (sets HttpContext.User); authorization decides what they may do using roles, claims and policies.

  • Authentication reads credentials (cookie, JWT bearer token, API key) and builds a ClaimsPrincipal. Authorization checks that principal against requirements.
  • JWT bearer: the client sends Authorization: Bearer <token>. The API validates the signature, issuer, audience and expiry, then maps claims to User. It is stateless; no server session.
  • Status codes: 401 Unauthorized = not authenticated (missing or invalid token). 403 Forbidden = authenticated but not allowed.
  • Apply rules with [Authorize], [Authorize(Roles = "Admin")], [Authorize(Policy = "...")], [AllowAnonymous], or .RequireAuthorization(...) on minimal API endpoints and groups.
  • Policy-based authorization: a policy is a set of requirements (role, claim, custom IAuthorizationRequirement + handler). Use it for rules like “owns the resource” or “age ≥ 18”.
  • Keep access tokens short-lived and use refresh tokens. Do not put secrets or personal data in a JWT payload; it is only Base64Url-encoded, not encrypted.

Interview questions

  • Difference between authentication and authorization?
  • How does JWT bearer authentication work in ASP.NET Core?
  • How would you revoke a JWT before it expires?

Data access & testing

EF Core: DbContext, tracking, migrations, loading & N+1

EF Core maps LINQ to SQL through a scoped DbContext; performance comes from no-tracking reads, projections, eager loading and avoiding N+1 queries.

  • DbContext is a unit of work: it tracks loaded entities and saves all changes in one SaveChanges transaction. It is not thread-safe and is registered as scoped. AddDbContextPool reuses instances.
  • Tracking queries (default) store a snapshot of each entity so changes are detected. AsNoTracking() skips that for read-only data: faster and less memory. AsNoTrackingWithIdentityResolution() still de-duplicates entities.
  • Migrations version the schema from your model: dotnet ef migrations add AddOrders, dotnet ef database update, or generate an idempotent SQL script / migration bundle for production deployments.
  • Loading related data: eager (Include / ThenInclude), explicit (Entry(x).Collection(...).LoadAsync()), lazy (proxies + virtual navigations, loads on first access).
  • N+1 problem: one query for parents plus one query per parent for children, usually from lazy loading in a loop. Fix with Include, a projection with Select, or batching.
  • Large Include graphs can cause a cartesian explosion; AsSplitQuery() runs one SQL query per collection instead.
  • Bulk updates and deletes without loading entities: ExecuteUpdateAsync / ExecuteDeleteAsync (EF Core 7+). Raw SQL: FromSql($"...") with interpolation is parameterized and safe.

Interview questions

  • What is the N+1 problem and how do you fix it in EF Core?
  • Tracking vs no-tracking queries?
  • Why is DbContext scoped and not singleton?
  • How do you apply migrations in production?

Testing: xUnit & WebApplicationFactory

Unit-test classes with xUnit and fakes; integration-test the real pipeline in memory with WebApplicationFactory.

  • xUnit: [Fact] for a single test, [Theory] with [InlineData] / [MemberData] for data-driven tests. A new test class instance is created for each test, so use the constructor for setup and IDisposable for teardown.
  • Share expensive setup with fixtures: IClassFixture<T> (per class) and collection fixtures (across classes). IAsyncLifetime gives async setup and teardown.
  • Mock dependencies through interfaces with Moq or NSubstitute, or write simple fakes. Inject TimeProvider instead of calling DateTime.UtcNow so time is testable.
  • WebApplicationFactory<Program> (package Microsoft.AspNetCore.Mvc.Testing) boots the real app on an in-memory TestServer and gives you an HttpClient. Middleware, DI, routing and filters all run.
  • Override services with WithWebHostBuilder(b => b.ConfigureTestServices(...)), for example to swap the database or fake an external API.
  • Top-level Program needs to be visible to the test project: older templates add public partial class Program { }; in .NET 10 a source generator makes it public for you.

Interview questions

  • Fact vs Theory in xUnit?
  • How do you integration-test an ASP.NET Core API?
  • How does xUnit handle setup and teardown compared to NUnit/MSTest?