C# & .NET Interview Questions
C# and .NET runtime guide: CLR execution, garbage collection generations, async/await state machines, memory spans, and ASP.NET Core middleware pipelines.
Practice C# & .NET Interview Questions
Showing 16 of 16 technical questions with engineering explanations
How do value types (struct) and reference types (class) differ in .NET memory layout, and what is boxing?
Senior Engineering Answer
Value types (structs, primitives, enums) store their data directly inline—on the stack for local variables or embedded inside containing objects/arrays on the heap—and are copied by value on assignment. Reference types (classes, interfaces, delegates, strings) always allocate on the managed heap and store a pointer reference in variables. Boxing occurs when a value type is cast to object or an interface it implements (or passed to non-generic APIs), allocating a heap wrapper object and copying the value into it, creating GC pressure.
int x = 42; object boxed = x; // Boxing: allocates on heap int unboxed = (int)boxed; // Unboxing: runtime type check + copy
Declaring a large mutable struct (>16 bytes) and passing it by value across hot methods: copying a 64-byte struct repeatedly can be slower than passing a readonly struct with `in` or using a class.
What is the difference between IEnumerable<T> and IQueryable<T>, and how does LINQ deferred execution work?
Senior Engineering Answer
LINQ queries on IEnumerable<T> and IQueryable<T> use deferred execution: building `.Where().Select()` constructs a query pipeline without running it until enumerated (`foreach`, `.ToList()`, `.FirstOrDefault()`). IEnumerable<T> takes `Func<T, bool>` delegates and executes filters in-memory inside the .NET process. IQueryable<T> takes `Expression<Func<T, bool>>` expression trees, allowing providers like EF Core to translate the tree into SQL and execute filtering on the database server.
// Runs WHERE in SQL: IQueryable<User> query = db.Users.Where(u => u.IsActive); // Materializes once: var activeUsers = await query.Take(50).ToListAsync();
Calling `.AsEnumerable()` or `.ToList()` before `.Where(...)`: this pulls the entire database table over the network into .NET memory before filtering.
How do string, StringBuilder, and string.Create differ for text manipulation in C#?
Senior Engineering Answer
System.String is immutable in .NET, so concatenating strings in a loop allocates a new string and copies previous characters on every iteration—O(n^2) allocations. StringBuilder maintains a mutable char buffer (growing via chunks) for dynamic multi-step concatenation in O(n) time. When the final length is known upfront, `string.Create(length, state, SpanAction)` allocates the exact final string once and lets you write characters directly into its internal buffer via `Span<char>` with zero intermediate allocations.
string formatted = string.Create(11, 42, (span, id) => {
"USER-".CopyTo(span);
id.TryFormat(span[5..], out _, "D6");
}); // "USER-000042"Using `string.Concat` or `+` for 2-3 known operands and wrapping them in a StringBuilder: for a fixed small number of parts, interpolated strings (`$"{a}-{b}"`) or `string.Concat` are faster than allocating a StringBuilder.
How do IDisposable, using statements, and IAsyncDisposable manage unmanaged resources?
Senior Engineering Answer
The CLR Garbage Collector tracks managed heap memory, not OS handles like file descriptors, sockets, or database connections. Types wrapping unmanaged resources implement `IDisposable.Dispose()` (or `IAsyncDisposable.DisposeAsync()` for async flush/close). The `using` / `await using` declaration compiles to a `try { ... } finally { resource?.Dispose(); }` block, guaranteeing deterministic cleanup even when exceptions occur without waiting for GC finalizers.
await using var conn = new SqlConnection(connStr);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("SELECT 1", conn);
return await cmd.ExecuteScalarAsync(ct);Adding a finalizer (`~MyClass()`) to every IDisposable class: finalizers promote objects to Gen 1/2 via the finalization queue, hurting GC throughput; only use finalizers (or preferably `SafeHandle`) when directly owning raw OS handles.
Explain ASP.NET Core Dependency Injection lifetimes (Transient, Scoped, Singleton) and the captive dependency bug.
Senior Engineering Answer
Transient creates a new instance every time the service is resolved. Scoped creates one shared instance per DI scope (one per HTTP request in ASP.NET Core, ideal for EF Core DbContext). Singleton creates a single instance for the lifetime of the application host. A captive dependency occurs when a Singleton injects a Scoped (or short-lived Transient) service: the Scoped instance gets captured by the Singleton and stays alive forever across requests, breaking thread safety and leaking DbContext state.
// Inject IServiceScopeFactory inside a Singleton BackgroundService to use Scoped services using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
Disabling `ValidateScopes` in development: ASP.NET Core's default development host enables scope validation precisely to throw an exception on startup if a Singleton captures a Scoped service.
How does the Roslyn compiler transform async/await into a state machine, and what does ConfigureAwait(false) do?
Senior Engineering Answer
Roslyn rewrites every `async` method into a compiler-generated struct implementing `IAsyncStateMachine` (boxed onto the heap only if the method actually suspends at an incomplete await). At each `await`, if the awaitable is incomplete, `AwaitUnsafeOnCompleted` hooks a continuation callback to `MoveNext()` and returns control to the caller. When resumed, by default `await` captures `SynchronizationContext.Current` (or non-default `TaskScheduler`) to marshal continuation back to the UI/request context. `ConfigureAwait(false)` skips capturing that context, avoiding UI-thread deadlocks when blocking synchronously and reducing overhead in general-purpose libraries.
public async Task<string> FetchAsync(HttpClient http, CancellationToken ct)
{
using var resp = await http.GetAsync("/health", ct).ConfigureAwait(false);
return await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
}Calling `.Result` or `.Wait()` on a Task inside UI/legacy ASP.NET contexts with a single-threaded SynchronizationContext: the continuation tries to resume on the blocked thread, causing a classic deadlock.
Compare Task vs ValueTask (and ValueTask<T>): when is ValueTask appropriate and what are its usage restrictions?
Senior Engineering Answer
`Task<T>` is a heap-allocated reference type, so every async call that completes asynchronously (or synchronously with a non-cached result) allocates a `Task<T>` object. `ValueTask<T>` is a discriminated union struct wrapping either a raw `T` result (zero allocation on synchronous completion, such as cache hits), a `Task<T>`, or a pooled `IValueTaskSource<T>` (zero allocation even when async, used in `Socket` and `Pipelines`). However, a `ValueTask<T>` backed by a pooled `IValueTaskSource` must NEVER be awaited more than once, awaited concurrently, or accessed via `.Result` before `IsCompleted` is true.
public ValueTask<User?> GetUserAsync(long id, CancellationToken ct)
{
if (_cache.TryGetValue(id, out var user))
return ValueTask.FromResult<User?>(user); // Zero heap allocation
return new ValueTask<User?>(LoadFromDbAsync(id, ct));
}Returning `ValueTask<T>` across public CRUD/business interfaces by default: callers frequently store `Task` in dictionaries or await twice with `Task.WhenAll`; only use `ValueTask<T>` on measured high-frequency hot paths.
How do Span<T>, ReadOnlySpan<T>, and Memory<T> enable zero-allocation slicing and parsing?
Senior Engineering Answer
`Span<T>` is a `ref struct` (a managed interior pointer + length) that can point uniformly into stack memory (`stackalloc`), managed heap arrays/strings, or unmanaged native memory. Slicing a span (`span[2..6]`) adjusts the pointer and length with zero heap allocations or array copies. Because `Span<T>` contains a managed interior pointer that cannot safely live on the heap, the compiler forbids boxing it, capturing it in lambdas, or keeping it across `await` boundaries in `async` methods; for async boundaries, use `Memory<T>` / `ReadOnlyMemory<T>` and call `.Span` synchronously between awaits.
static int SumCsvInts(ReadOnlySpan<char> line)
{
int sum = 0;
foreach (Range r in line.Split(',')) // .NET 9 zero-alloc Span Split
sum += int.Parse(line[r]);
return sum;
}Trying to store a `Span<T>` as a field on a normal class or pass it into an `async` method: only `ref struct` types can hold a `Span<T>`, and `async` state machines live on the heap when suspended.
Explain the .NET Generational Garbage Collector: Gen 0/1/2, LOH, POH, and Server vs Workstation GC.
Senior Engineering Answer
The CLR GC uses the generational hypothesis (most objects die young): new small objects allocate sequentially via bump-pointer in Gen 0; survivors promote to Gen 1 and then Gen 2 (long-lived). Objects >= 85,000 bytes bypass Gen 0/1 onto the Large Object Heap (LOH), which is swept without compaction by default to avoid costly memory copies. .NET 5+ added the Pinned Object Heap (POH) for pinned buffers (`GC.AllocateArray<byte>(n, pinned: true)`), preventing pinning fragmentation in Gen 0/2. Server GC (`<ServerGarbageCollection>true</ServerGarbageCollection>`) creates a dedicated heap and GC thread per CPU core for high-throughput servers, whereas Workstation GC uses a single heap optimized for lower memory footprint.
// Allocate pinned buffer on POH instead of pinning Gen 0 arrays with GCHandle byte[] dmaBuffer = GC.AllocateArray<byte>(4096, pinned: true);
Running `ServerGC` inside a memory-constrained container (e.g., 512MB RAM on a 64-core host) without tuning: Server GC scales segments per core and can exceed cgroup memory limits if `DOTNET_GCHeapHardLimit` isn't respected.
What causes .NET ThreadPool starvation, and how does the hill-climbing algorithm recover (or fail to recover)?
Senior Engineering Answer
The .NET ThreadPool starts with a small number of worker threads (~CPU count) and injects additional threads slowly (roughly 1-2 per second once starvation is detected) using a hill-climbing heuristic to avoid thread-thrashing. ThreadPool starvation occurs when requests perform synchronous blocking calls (`.Result`, `.Wait()`, `Thread.Sleep`, sync-over-async, or unawaited heavy sync I/O) on ThreadPool threads. Incoming requests queue up in the global/local work-stealing queues while existing threads sit idle waiting on I/O, causing p99 latency to spike into seconds even at low CPU utilization.
// Diagnostics: detect ThreadPool queue buildup via EventCounters or dotnet-counters // dotnet-counters monitor -p <pid> --counters System.Runtime[threadpool-queue-length,threadpool-thread-count]
Working around sync-over-async starvation by cranking `ThreadPool.SetMinThreads(500, 500)`: this masks the root bug while wasting ~500MB of stack memory and causing severe context-switching overhead under real load.
Compare System.Threading.Channels and System.IO.Pipelines for high-throughput producer/consumer workloads.
Senior Engineering Answer
`Channel<T>` (bounded or unbounded) is the modern async-native replacement for `BlockingCollection<T>`, offering non-blocking `WaitToReadAsync`/`ReadAllAsync` and backpressure via `BoundedChannelFullMode.Wait` (or DropOldest/DropNewest) for structured object pipelines. `System.IO.Pipelines` (`Pipe`) is designed specifically for streaming byte parsing (used inside Kestrel): it manages pooled `IMemoryOwner<byte>` segments internally, lets producers write directly into pooled buffers without copying, and lets parsers inspect incomplete frames via `ReadOnlySequence<byte>` and call `AdvanceTo(consumed, examined)` to avoid re-scanning.
var channel = Channel.CreateBounded<WorkItem>(new BoundedChannelOptions(1024)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true
});Using `Channel.CreateUnbounded<T>()` in front of a slower downstream consumer (like a database writer): an unbounded queue absorbs bursts until the process hits OutOfMemoryException.
How do C# record classes, record structs, and pattern matching simplify immutable domain models?
Senior Engineering Answer
`record class` provides value-based equality (`Equals`, `GetHashCode`, `==`), compiler-generated `with` non-destructive mutation expressions, and `init`-only properties on a reference type. `readonly record struct` provides value-based equality on a stack/inline value type without heap allocation (and avoids slow reflection-based `ValueType.Equals`). Combined with C# switch expressions, list patterns (`[var head, .. var tail]`), and property patterns, domain state transitions become concise and compiler-checked.
public readonly record struct Money(decimal Amount, string Currency);
static decimal ApplyDiscount(Money m) => m switch
{
{ Currency: "USD", Amount: >= 100m } => m.Amount * 0.90m,
{ Amount: > 0m } => m.Amount,
_ => throw new ArgumentOutOfRangeException(nameof(m))
};Using `record struct` without `readonly` when expecting immutability: positional `record class` parameters generate `init` properties, whereas positional `record struct` parameters generate mutable `get; set;` properties unless marked `readonly record struct`.
How do Roslyn Source Generators and NativeAOT change .NET startup, reflection, and serialization?
Senior Engineering Answer
Traditional .NET libraries (reflection-based JSON serialization, DI scanning, Regex, EF Core models) generate IL at runtime via `Reflection.Emit` or inspect metadata dynamically, increasing cold-start time, memory, and blocking NativeAOT trimming. Incremental Source Generators (`IIncrementalGenerator`) run inside the Roslyn compiler pipeline to emit strongly typed C# source at build time (e.g., `System.Text.Json`'s `[JsonSerializable]`, `[GeneratedRegex]`, `[LoggerMessage]`). NativeAOT compiles IL ahead-of-time into a standalone native binary with zero JIT, cutting startup latency and RSS dramatically, provided dynamic `Reflection.Emit` and unrooted reflection are eliminated.
[JsonSerializable(typeof(OrderDto))]
internal partial class AppJsonContext : JsonSerializerContext { }
// Zero-reflection, NativeAOT-safe serialization
string json = JsonSerializer.Serialize(order, AppJsonContext.Default.OrderDto);Enabling `<PublishAot>true</PublishAot>` without resolving IL2xxx/IL3xxx trimmer/AOT warnings: the trimmer may strip types accessed only via reflection (`Activator.CreateInstance`, `Assembly.GetTypes`), causing runtime failures only in published builds.
Compare lock / System.Threading.Lock (.NET 9), SemaphoreSlim, and lock-free Interlocked operations.
Senior Engineering Answer
`lock (obj)` (using `Monitor.Enter/Exit`, or the dedicated `System.Threading.Lock` type in .NET 9+ which avoids Monitor's sync-block-index overhead) provides fast mutual exclusion for synchronous critical sections—but cannot be held across `await`. `SemaphoreSlim(1, 1)` offers `WaitAsync(ct)` for async mutual exclusion and bounded concurrency gating. For single-word atomic updates or lock-free state machines, `Interlocked.CompareExchange` / `Interlocked.Add` execute CPU atomic instructions (`LOCK CMPXCHG` on x86) with zero kernel transitions or lock contention.
// Lock-free atomic max update using CompareExchange loop
long prev, next;
do {
prev = Volatile.Read(ref _maxLatencyTicks);
if (sampleTicks <= prev) break;
next = sampleTicks;
} while (Interlocked.CompareExchange(ref _maxLatencyTicks, next, prev) != prev);Writing `lock (this)`, `lock (typeof(MyClass))`, or `lock (stringLiteral)`: public or interned objects can be locked by unrelated external code, causing unpredictable cross-component deadlocks.
How do ArrayPool<T>, ObjectPool<T>, and RecyclableMemoryStream reduce Gen 2 / LOH pressure in high-RPS services?
Senior Engineering Answer
Allocating temporary buffers >= 85KB per request places them directly on the LOH, triggering expensive Gen 2 blocking collections and memory fragmentation. `ArrayPool<byte>.Shared.Rent(size)` checks out reusable bucketed arrays via thread-local caches and returns them with `Return(buf, clearArray)` in a `finally` block (keep in mind `Rent` may return an array larger than requested, so always slice to `size`). For variable-length streams like serialization buffers, `Microsoft.IO.RecyclableMemoryStream` backs streams with pooled fixed-size blocks so no LOH allocation ever occurs.
byte[] rented = ArrayPool<byte>.Shared.Rent(minLength: 16_384);
try {
Span<byte> slice = rented.AsSpan(0, 16_384);
ProcessBuffer(slice);
} finally {
ArrayPool<byte>.Shared.Return(rented, clearArray: true);
}Forgetting `clearArray: true` when returning buffers holding sensitive PII/tokens to `ArrayPool<T>.Shared`, or continuing to reference the rented array after `Return()` (use-after-return data corruption).
How does Kestrel handle socket I/O, HTTP/2 multiplexing, and zero-allocation request pipelining internally?
Senior Engineering Answer
Kestrel uses a SocketTransport backed by OS async I/O (epoll on Linux, IOCP on Windows, kqueue on macOS) and `System.IO.Pipelines` to read raw bytes into pooled 4KB slab buffers. Rather than allocating `string` objects for every HTTP header on every request, Kestrel parses request lines and headers directly over `ReadOnlySpan<byte>`/`SequenceReader<byte>` and interns known/static header names and methods, reusing `HttpContext` and `Pipe` structures across keep-alive requests via `IHttpContextFactory`/connection pooling. Over HTTP/2 and HTTP/3 (QUIC), Kestrel multiplexes concurrent streams over a single connection with flow-control windows and HPACK/QPACK header compression.
// Custom Kestrel tuning for high-connection workloads
builder.WebHost.ConfigureKestrel(options => {
options.Limits.MaxConcurrentConnections = 50_000;
options.Limits.Http2.MaxStreamsPerConnection = 200;
});Reading `Request.Body` synchronously or buffering multi-megabyte uploads into `MemoryStream` / `byte[]` inside middleware instead of streaming `PipeReader` / `Stream` directly to storage.
C# & .NET Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis C# & .NET preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Computer Science & Languages.
How do value types (struct) and reference types (class) differ in .NET memory layout, and what is boxing?
What is the difference between IEnumerable<T> and IQueryable<T>, and how does LINQ deferred execution work?
How do string, StringBuilder, and string.Create differ for text manipulation in C#?
How do IDisposable, using statements, and IAsyncDisposable manage unmanaged resources?
Explain ASP.NET Core Dependency Injection lifetimes (Transient, Scoped, Singleton) and the captive dependency bug.
How does the Roslyn compiler transform async/await into a state machine, and what does ConfigureAwait(false) do?
Frequently Asked Technical Interview Questions (C# & .NET)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
What is the difference between Task and ValueTask in .NET?
How do Span<T> and Memory<T> achieve zero-allocation parsing?
What is a captive dependency in ASP.NET Core Dependency Injection?
How does the .NET Garbage Collector manage Gen 0, Gen 1, Gen 2, and the LOH?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.