C# Language, CLR Internals & High-Performance Engineering Master Interview Bank
CLR memory management, GC generations, Span<T>, Memory<T>, Async/Await State Machine, Channels, Native AOT, SIMD vectorization, and lock-free concurrency.
Curriculum Roadmap & Learning Path
3 StagesPart 1: Core Language, CLR & Memory Architecture (1 - 10)
10 QuestionsWhat is the Common Language Runtime (CLR) and the Common Intermediate Language (CIL)?
CIL (Common Intermediate Language): The platform-agnostic bytecode generated when C# code is compiled by the Roslyn compiler • CLR (Common Language Runtime): The execution engine of .NET that provides memory management, garbage collection, thread pool management, type.
How does the .NET Garbage Collector work (Generations 0, 1, 2 and LOH)?
The .NET Garbage Collector divides managed heap objects into 3 generations based on age, plus a Large Object Heap: Generation 0: Short-lived objects (temporary local variables) • Generation 1: Buffer generation • Generation 2: Long-lived objects (static singletons, application caches) • LOH (Large Object Heap): Objects >= 85,000 bytes.
What is the difference between Value Types and Reference Types in C#?
Value Types (struct, enum, int, bool, double): Stored inline where declared (usually on the stack for local variables, or inside the heap object • Reference Types (class, interface, delegate, record, string): Allocated on the managed heap.
What are `Span<T>`, `ReadOnlySpan<T>`, and `Memory<T>`, and why are they critical for high performance?
SpanT: A ref struct that represents a contiguous region of arbitrary memory (managed heap array, unmanaged native heap, or stack-allocated • It enables zero-allocation string slicing, parsing, and buffer manipulation • Because SpanT is a ref struct, it can ONLY live on the stack (cannot be boxed or captured in async methods).
What are Primary Constructors, Records, and `with` expressions in C# 10/12?
Records: Reference types or structs with built-in value-based equality (Equals, GetHashCode), immutability, and automatic deconstruction • with expressions: Non-destructive mutation (creates a shallow copy with modified properties).
How does the `async` / `await` State Machine work under the hood?
When the Roslyn compiler encounters an async method, it rewrites the method into a generated struct implementing IAsyncStateMachine: When execution hits await task, it checks task.IsCompleted • If completed, execution continues synchronously without thread switching.
What is Boxing and Unboxing, and how do you avoid its performance penalty?
Boxing: Converting a Value Type to a Reference Type (or interface), allocating an object on the managed heap and copying the value into it • Unboxing: Extracting the value type back out from the heap object to the stack • Penalty: Heavy GC pressure and CPU overhead in tight loops.
What is the difference between `IEnumerable<T>`, `IQueryable<T>`, and `IAsyncEnumerable<T>`?
IEnumerableT: In-memory collection iterator • IQueryableT: Represents a deferred query using Expression Trees • IAsyncEnumerableT (C# 8+): Streams asynchronous sequences of data item-by-item (await foreach) without buffering the entire dataset in server memory.
What are String Interning and `StringBuilder` internals?
String Immutability: Modifying a string creates a new string on the heap • String Interning: The CLR maintains an internal hash table (intern pool) of unique string literals to reuse identical strings across the AppDomain • StringBuilder: A mutable buffer backed by an array of char[].
What is the difference between `Task.Run` vs. `Task.Yield` vs. `ValueTask<T>`?
Task.Run: Queues CPU-bound work to run on a background ThreadPool thread • Task.Yield: Forces the current method to yield execution asynchronously, re-queuing the continuation back to the dispatcher.
Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)
14 QuestionsWhat is the difference between IEnumerable<T>, ICollection<T>, IList<T>, and IReadOnlyList<T>?
IEnumerableT: Read-only forward-only iteration • ICollectionT: Inherits IEnumerableT • IListT: Inherits ICollectionT • IReadOnlyListT: Exposes Count and indexed read access (this[int index]), communicating immutability to API consumers.
How does Generics Covariance (out) and Contravariance (in) work in C#?
Variance defines whether generic types with polymorphic relationships can be substituted for one another.: Covariance (out): Allows you to use a more derived type than originally specified (output only) • Contravariance (in): Allows you to use a more generic (base) type than originally specified (input only).
What are ref struct, in parameters, and readonly struct in high-performance C#?
ref struct: A value type that is strictly stack-allocated • readonly struct: Informs the compiler that all fields are immutable, allowing the compiler to pass the struct by reference without creating • in parameter: Passes a struct by readonly ref pointer rather than copying all struct bytes across stack frames.
How does modern Pattern Matching work in C# (Property, Positional, Relational & List patterns)?
Pattern matching tests values against shapes and types cleanly without nested if-else cascades or explicit casting.
What are Expression Trees and how does LINQ translate C# expressions into SQL?
While Func compiles lambda code directly into IL machine bytecode, Expression> represents code as an abstract syntax tree (AST) data structure that can be inspected, traversed, and rewritten at runtime.
How do IDisposable and IAsyncDisposable work, and what is the standard Dispose(bool) pattern?
The .NET Garbage Collector reclaims managed heap memory, but has no knowledge of unmanaged resources (file handles, database sockets, OS window handles). IDisposable provides deterministic release of unmanaged resources via using blocks.
What is System.Threading.Channels and how does it outperform BlockingCollection?
System.Threading.Channels is a high-performance, fully asynchronous lock-free library for building producer-consumer patterns without thread blocking. BlockingCollectionT blocks OS threads synchronously when waiting for items or buffer capacity.
What are Memory Barriers, volatile, and Interlocked operations in the .NET Memory Model?
Interlocked: Hardware-level atomic operations (CAS / atomic increment) • volatile: Informs the JIT compiler and CPU cache coherence controllers that reads must have acquire semantics and writes must have release.
What is ArrayPool<T> and how does memory pooling eliminate Garbage Collection Gen 0 pressure?
Allocating temporary byte or char arrays in high-throughput services (e.g., HTTP request buffers) floods Gen 0 with short-lived objects, triggering frequent GC pauses. ArrayPoolT.Shared rents pre-allocated arrays from a shared memory pool and returns them after use, reducing allocations to zero.
What are Roslyn Source Generators and how do they replace runtime reflection?
Source Generators are C# compiler plugins that run during compilation. They inspect user code syntax trees and generate additional C# source code files before emitting bytecode.: Zero Runtime Reflection Overhead: Generates strongly typed, direct code at compile time.
How does System.Text.Json Source Generation work and why is it essential for Native AOT?
Default JSON serializers inspect object properties at runtime using reflection. With JsonSerializerContext, Roslyn source generators generate specialized serialization and deserialization code at compile time.
What are Hardware Intrinsics and SIMD vectorization in modern .NET?
SIMD (Single Instruction, Multiple Data) executes the same mathematical or comparison operation across multiple data elements simultaneously within 128-bit, 256-bit (AVX2), or 512-bit (AVX-512) CPU vector registers.
How do you identify and prevent ThreadPool Starvation and sync-over-async deadlocks?
Calling .Result or .Wait() on an asynchronous task blocks the current thread until the task completes. Under high concurrent load, this locks all available ThreadPool worker threads, leaving zero threads to actually complete the pending tasks—causing ThreadPool Starvation and system freeze.
What is WeakReference<T> and ConditionalWeakTable in .NET?
A WeakReferenceT references an object without preventing the Garbage Collector from collecting it. ConditionalWeakTable allows you to attach metadata to an object without altering the class or creating memory leaks (when the key is collected, the value is automatically freed).
Part 3: CLR Internals, Native AOT & Production Diagnostics (25 - 35)
26 QuestionsHow does Tiered Compilation and Dynamic PGO (Profile-Guided Optimization) work in .NET 8/9?
Tier 0: Methods are compiled quickly with no optimizations for fast application startup • Tier 1: As methods exceed call thresholds, the JIT re-compiles them with full optimizations • Dynamic PGO: The JIT injects lightweight instrumentation into Tier 0 code to observe runtime behavior (e.g., concrete types in interfaces).
What is Native AOT in .NET 8/9 and what are its trade-offs?
Native AOT compiles .NET C# code directly into architecture-specific machine code (ELF/PE) with no JIT compiler or IL interpreter.: Starts in under 10ms • 50% less memory usage • Single self-contained binary with no .NET runtime installation required • No dynamic reflection without explicit compiler preservation hints.
How does Unsafe code, stackalloc, and P/Invoke interop work in C#?
C# supports pointer arithmetic within unsafe code blocks. stackalloc allocates memory directly on the execution stack rather than the managed heap, requiring zero garbage collection.
How do you capture and diagnose Memory Leaks in production .NET applications using dotnet-dump?
Use the cross-platform CLI tool dotnet-dump.
How do you diagnose CPU 100% spikes in .NET using dotnet-trace and SpeedScope flamegraphs?
Capture live execution CPU sampling traces with dotnet-trace.
Compare SpinLock, Monitor (lock), ReaderWriterLockSlim, and SemaphoreSlim in .NET?
lock (Monitor): Hybrid lock; spins briefly before kernel sleep • SpinLock: Never transitions to kernel mode; continuously spins on CPU • ReaderWriterLockSlim: Multiple concurrent readers, single exclusive writer • SemaphoreSlim: Supports async locking (await semaphore.WaitAsync()).
What is the SafeHandle pattern and how does it prevent resource leaks across asynchronous exceptions?
SafeHandle wraps native OS operating handles in a managed object derived from CriticalFinalizerObject, guaranteeing handle closure even in the event of thread aborts or out-of-memory errors.
What are Extension Methods in C# and how are they lowered by the compiler?
Extension methods allow adding methods to existing types without modifying the source. The compiler simply rewrites myObject.MyExtension() into a static method call MyExtensionClass.MyExtension(myObject).
How does the C# Compiler lower Lambda Expressions and Closures into compiler-generated display classes?
When a lambda captures an outer local variable (a closure), the Roslyn compiler synthesizes an internal class (display class), promotes the local variable to a heap field on that class, and turns the lambda into an instance method of that class.
How do you write reliable micro-benchmarks in C# using BenchmarkDotNet?
BenchmarkDotNet runs multiple warmup and execution iterations in clean processes, measures GC allocations ([MemoryDiagnoser]), and calculates statistical standard deviation.
When should you choose C# / .NET over Go, Java, or Rust for enterprise distributed systems?
Choose C# and .NET for high-throughput enterprise systems requiring expressive language features (async/await, LINQ, pattern matching) combined with zero-allocation low-level performance (SpanT, Native AOT, SIMD) and premier tooling.
Value Types vs Reference Types: Stack, Heap, and Boxing.
Value Types (struct, enum, int, double, bool): Stored where declared (typically on the thread stack or inline inside containing objects) • Reference Types (class, interface, delegate, string, object): Stored on the managed heap.
Zero-Allocation Memory Slicing: `Span<T>` and `ReadOnlySpan<T>`.
Prior to SpanT, string manipulation (substring, split) allocated millions of short-lived strings on the heap, triggering heavy GC pauses.: SpanT / ReadOnlySpanT: A stack-only ref struct representing a contiguous region of arbitrary memory (managed array, native memory, or.
Async/Await: `Task` vs `ValueTask<T>`.
TaskT: A reference type allocated on the heap every time an async method is called • ValueTaskT: A value type struct • Rule: Use ValueTaskT for high-throughput methods that frequently return synchronously from cache.
.NET Garbage Collection: Generational GC and the Large Object Heap (LOH).
The .NET CLR uses a generational tracing garbage collector: Gen 0: Freshly allocated short-lived objects (collected in sub-milliseconds) • Gen 1: Buffer generation acting as a ramp between short-lived and long-lived data • Gen 2: Long-lived objects (static caches, database connection pools).
Pattern Matching in Modern C# (C# 9 - 12+).
Pattern matching tests expressions against shapes, types, and values: Property Patterns: Inspects object properties directly without nested null-checks • Relational & Logical Patterns: Matches numeric thresholds with and, or, not, >, < • List Patterns (C# 11+): Matches elements within arrays or lists ([var first.., var last]).
Records and Immutability: `record class` vs `record struct`.
Records are nominal types designed for immutable data: Auto-generates value-based equality (Equals(), ==), hash code, and ToString() • init accessors: Properties can only be assigned during object construction • Non-destructive Mutation (with expression): Creates a new copy with modified properties while preserving the original.
Delegates vs Expression Trees.
Delegates (Func): Compiled IL code executed directly by the CPU in memory (e.g. IEnumerable.Where()) • Expression Trees (Expression>): Data structure representing the AST (Abstract Syntax Tree) of the code.
Thread Synchronization: `lock`, `SemaphoreSlim`, and `Interlocked`.
lock(obj): Synchronous mutual exclusion monitor • SemaphoreSlim: Supports async non-blocking lock acquisition (await semaphore.WaitAsync()) • Interlocked (Increment, CompareExchange): Atomic CPU-level lock-free operations with zero thread-blocking overhead.
LINQ Internals and Deferred Execution Traps.
LINQ uses Deferred (Lazy) Execution: query execution does not occur when the LINQ query is defined, but when enumerated (foreach.ToList().Count()): Multiple Enumeration Bug: Calling .Count() and then .ToList() on an IEnumerable that executes an HTTP request or DB query executes the expensive.
The IDisposable and IAsyncDisposable Pattern.
Managed GC does not automatically release unmanaged OS resources (file handles, database connections, sockets): IDisposable: Releases resources synchronously via .Dispose() • IAsyncDisposable (C# 8+): Asynchronously releases unmanaged resources (await using var stream = ...) without blocking the thread pool during.
Nullable Reference Types (NRT): Eliminating NullReferenceExceptions.
Enabled via Nullableenable in .csproj: Distinguishes nullable strings (string? • The compiler runs static flow analysis, flagging any code path where a nullable variable is dereferenced without a prior null-check • Null-Forgiving Operator (!): Explicitly tells the compiler that a variable is guaranteed non-null at runtime (user!.Profile).
C# Source Generators: Compile-Time Metaprogramming.
Source Generators run as part of the dotnet build compiler pipeline: Inspects code syntax trees and generates additional C# source files added directly to the compilation.
Native AOT Compilation in .NET 8 / 9.
Native AOT compiles C# directly into machine code (ELF/PE) without intermediate IL bytecode or the JIT compiler: Starts in < 10\text{ms} with immediate peak performance • Cuts binary memory footprint by 80% and eliminates JIT warm-up latency • Requires trim-safe code and source-generated reflection.
Dependency Injection: The Captive Dependency Problem.
.NET provides three DI lifetimes: Transient: Created every time requested • Scoped: Created once per client request (HTTP request) • Singleton: Created once for the application lifetime • The Captive Dependency Bug: If a Singleton service injects a Scoped service (like an EF Core DbContext), the scoped service is kept alive.
High-Performance I/O with `System.IO.Pipelines`.
Created to power Kestrel (the fastest web server in TechEmpower benchmarks): Replaces raw Stream reading with PipeReader and PipeWriter • Manages pooled memory buffers automatically, eliminating buffer copying and reducing GC allocations to zero when processing continuous.