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
- .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.
- 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.
- 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. - Boxing copies a value type into a new heap object when it is treated as
objector an interface. Unboxing casts it back and copies again. Generics avoid it. recordgives value-based equality, a readableToStringandwithcopies.record classis a reference type;record structis a value type.stringis immutable: every change makes a new string. Build strings in loops withStringBuilder.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.- Nullable reference types (
string?) are compile-time warnings only.Nullable<T>(int?) is a real runtime wrapper for value types. Func<>returns a value,Action<>returnsvoid. Aneventis a delegate that outsiders can only+=/-=, not invoke or overwrite.- 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. awaitfrees the thread while waiting. Never block on async code with.Result/.Wait(). UseConfigureAwait(false)in library code. Avoidasync voidexcept event handlers.- 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. - Use
throw;to rethrow.throw ex;resets the stack trace. Catch specific exceptions and usewhenfilters. - Middleware runs in registration order on the way in and in reverse on the way out.
UseAuthenticationmust come beforeUseAuthorization. - DI lifetimes: Singleton (one per app), Scoped (one per request), Transient (new every time). Never inject a scoped service into a singleton (captive dependency).
- EF Core:
DbContextis scoped and not thread-safe. UseAsNoTracking()for read-only queries,Includeto avoid N+1, and project withSelectto 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
.dllfiles, 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, anystruct. 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
objector 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,outandinpass a reference to the caller's variable. ref: caller must initialize, method may read and write.out: method must assign before returning (used byTryParse).in: read-only reference, useful for large structs.paramsaccepts 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
refandout?
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
PointorMoney. - record (C# 9) is a class with compiler-generated value equality,
ToString, deconstruction andwithexpressions.record struct(C# 10) does the same for value types. - Positional records like
record Person(string Name, int Age)create a primary constructor andinit-only properties (forrecord classandreadonly record struct). - A
withexpression 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.
stringis a reference type with value semantics:==andEqualscompare characters, not references.- Strings are immutable.
Replace,ToUpperand+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.
StringBuilderkeeps a growable buffer and builds once atToString(). - For a few pieces,
+, interpolation$"...",string.Concatorstring.Joinare fine and often faster than aStringBuilder. - 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/OrdinalIgnoreCasefor 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
==andEqualsfor 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 withHasValueandValue.GetValueOrDefault()avoids exceptions.- Nullable reference types (NRT), enabled with
<Nullable>enable</Nullable>(on in new templates), makestringmean “never null” andstring?mean “may be null”. - NRT is static analysis only: no runtime checks, and the compiled type is still
string. Public APIs should still validate withArgumentNullException.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 ifcustomeris not null. - Attributes such as
[NotNullWhen(true)],[MaybeNull]and[MemberNotNull]teach the compiler about your own null checks.
Interview questions
- Difference between
int?andstring?? - 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.usingcalls 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. PreferSafeHandle; callGC.SuppressFinalize(this)inDispose. IAsyncDisposablewithawait usingdisposes 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(orinit) 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
fieldkeyword: 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.
virtualallows overriding,overridereplaces it,sealedstops further overriding, andnewhides 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
overrideandnew?
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>(returnsvoid),Predicate<T>(returnsbool). Prefer them over custom delegate types. - A lambda (
x => x * 2) creates a delegate or, when assigned toExpression<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>. staticlambdas (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>andList<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, orallows ref struct(C# 13). - Variance on interfaces and delegates:
out Tis covariant (IEnumerable<string>toIEnumerable<object>),in Tis contravariant (Action<object>toAction<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>andIQueryable<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,Skipand friends return a query object. Work happens when youforeach, or callToList,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()orToList()too early pulls the whole table into memory and filters there. - Know the pairs:
First(throws if empty) vsFirstOrDefault;Single(throws if not exactly one);Any()vsCount() > 0;SelectvsSelectMany(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. finallyalways runs aftertry/catch(except when the process dies, for example from aStackOverflowException).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
catchblocks from most specific to most general. Avoid emptycatch {}and catchingExceptionexcept at app boundaries. - Exceptions are expensive. Use
TryParse/TryGetValueor result types for expected failures like invalid input.
Interview questions
- Difference between
throwandthrow 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):
paramscollections (params ReadOnlySpan<T>), the newSystem.Threading.Locktype,\eescape, partial properties. - C# 14 (.NET 10 LTS): extension members, the
fieldkeyword, null-conditional assignment (a?.B = c),nameofon unbound generics, more implicitSpanconversions. - C# 15 (.NET 11): union types (
public union Pet(Cat, Dog);), closed class hierarchies for exhaustive switches, collection expression arguments ([with(capacity: 10), ..items]), labeledbreak/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
Taskrepresents an operation that will complete later;Task<T>also carries a result.asynclets a method useawait; it does not create a thread by itself. - For I/O-bound work (HTTP, DB, files)
awaituses no thread while waiting. For CPU-bound work, useTask.Runto 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().Resultblocks the thread while the continuation waits for that same thread. In ASP.NET Core, blocking causes thread-pool starvation instead. async voidcannot be awaited and its exceptions crash the process; use it only for event handlers. ReturnTaskotherwise.ValueTask<T>avoids an allocation when results are often synchronous, but must be awaited only once. Pass aCancellationTokenthrough every async call.
Interview questions
- What actually happens at an
await? - Why can
.Resultdeadlock? - 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
HttpContextand anextdelegate.app.Use(...)adds one that can callnext;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 asInvokeAsyncparameters.
Interview questions
- What is middleware in ASP.NET Core?
- Difference between
Use,RunandMap? - 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 andInvokeAsync). - 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
DbContextshared across all requests). In Development, scope validation throws at startup or resolve time for this. - To use scoped services from a singleton or
BackgroundService, injectIServiceScopeFactoryand create a scope per unit of work. - The container disposes the
IDisposableservices 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 viaMapGroup. 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 checkModelStateautomatically; minimal APIs get built-in validation in .NET 10 withbuilder.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>/IActionResultin 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 fromASPNETCORE_ENVIRONMENT(orDOTNET_ENVIRONMENT). - Options pattern: bind a section to a class with
services.AddOptions<T>().Bind(...)orConfigure<T>(...), then injectIOptions<T>,IOptionsSnapshot<T>orIOptionsMonitor<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 storeOrderIdas 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 toUser. 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.
DbContextis a unit of work: it tracks loaded entities and saves all changes in oneSaveChangestransaction. It is not thread-safe and is registered as scoped.AddDbContextPoolreuses 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 +virtualnavigations, 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 withSelect, or batching. - Large
Includegraphs 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 andIDisposablefor teardown. - Share expensive setup with fixtures:
IClassFixture<T>(per class) and collection fixtures (across classes).IAsyncLifetimegives async setup and teardown. - Mock dependencies through interfaces with Moq or NSubstitute, or write simple fakes. Inject
TimeProviderinstead of callingDateTime.UtcNowso time is testable. WebApplicationFactory<Program>(packageMicrosoft.AspNetCore.Mvc.Testing) boots the real app on an in-memory TestServer and gives you anHttpClient. 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
Programneeds to be visible to the test project: older templates addpublic 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?