Skip to main content
InterviewHubPRO
HomeTracksSection 26: C# & CLR Internals (50 Qs)
Section 26 of 6450 Questions (1 Per Page)

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 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.3 Connected Milestones
50 of 50 Qs

Part 1: Core Language, CLR & Memory Architecture (1 - 10)

10 Questions
1
SeniorCode#System Design

What 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.

2
Senior#Memory Management#System Design

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.

3
Senior#System Design

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.

4
SeniorCode#Forms#Performance

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).

5
SeniorCode#System Design

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).

6
Senior#Async & Promises#System Design

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.

7
Senior#Forms#Performance

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.

8
Senior#Async & Promises#TypeScript

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.

9
Senior#System Design

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[].

10
Senior#System Design

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 Questions
11
SeniorCode#TypeScript

What 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.

12
SeniorCode#TypeScript

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).

13
SeniorCode#Forms#Performance

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.

14
SeniorCode#csharp#Concurrency

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.

15
SeniorCode#Databases & SQL#Data Structures

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.

16
SeniorCode#Async & Promises

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.

17
SeniorCode#Forms#Golang

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.

18
SeniorCode#csharp#Concurrency

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.

19
SeniorCode#Memory Management#Data Structures

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.

20
Senior#csharp#Concurrency

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.

21
SeniorCode#csharp#Concurrency

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.

22
Most AskedSeniorCode#csharp#Concurrency

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.

23
Senior#Async & Promises

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.

24
Senior#csharp#Concurrency

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 Questions
25
Senior#Performance

How 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).

26
Senior#csharp#CLR Internals

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.

27
SeniorCode#Memory Management#Data Structures

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.

28
SeniorCode#Memory Management

How do you capture and diagnose Memory Leaks in production .NET applications using dotnet-dump?

Use the cross-platform CLI tool dotnet-dump.

29
SeniorCode#Data Structures

How do you diagnose CPU 100% spikes in .NET using dotnet-trace and SpeedScope flamegraphs?

Capture live execution CPU sampling traces with dotnet-trace.

30
Senior#csharp#CLR Internals

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()).

31
Senior#Async & Promises

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.

32
Senior#csharp#CLR Internals

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).

33
Most AskedSenior#Closures & Scope

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.

34
Senior#csharp#CLR Internals

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.

35
Senior#System Design

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.

36
Senior#Memory Management#Data Structures

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.

37
SeniorCode#csharp#CLR Internals

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.

38
Most AskedSenior#Async & Promises

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.

39
Senior#Memory Management#Data Structures

.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).

40
SeniorCode#csharp#CLR Internals

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]).

41
SeniorCode#csharp#CLR Internals

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.

42
Senior#Data Structures

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.

43
Senior#csharp#CLR Internals

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.

44
Senior#csharp#CLR Internals

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.

45
Senior#Async & Promises

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.

46
Senior#csharp#CLR Internals

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).

47
Senior#csharp#CLR Internals

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.

48
Senior#csharp#CLR Internals

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.

49
Most AskedSenior#Dependency Injection

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.

50
Senior#Forms#Performance

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.