Brainbotox · Lessons · Exams

C# Interview Questions, Advanced: Deadlocks, Threads and Span (30 questions)

by lazizanie · Programming · C# / .NET · English

30 advanced C# interview questions for senior developers with model answers: garbage collector, Span and allocations, locks and thread safety, async internals, reflection, expression trees and variance.

Take this exam on Brainbotox, with marking →

30 questions. The model answers are folded under each one.

Question 1

Q1. The async deadlock. This WinForms button handler freezes the application for ever.

private void LoadButton_Click(object sender, EventArgs e)
{
    var text = GetDataAsync().Result;
    resultBox.Text = text;
}
private async Task<string> GetDataAsync()
{
    var response = await _http.GetStringAsync(_url);
    return response.Trim();
}

(a) Explain step by step why it deadlocks.

(b) Would the same code deadlock in ASP.NET Core? Why?

(c) Give two ways to fix it and say which one you prefer.

Model answer

(a) Why it deadlocks

  1. The click handler runs on the UI thread and calls GetDataAsync().
  2. At the await, the HTTP call is not finished. The awaiter captures the current SynchronizationContext (the UI one) and returns an incomplete task.
  3. Back in the handler, .Result blocks the UI thread until that task completes.
  4. The HTTP call ends. The rest of the method (return response.Trim()) is posted to the UI thread, because that is the captured context.
  5. The UI thread is blocked waiting for the task, and the task needs the UI thread to finish. Each waits for the other: deadlock.

(b) ASP.NET Core: no deadlock. ASP.NET Core has no SynchronizationContext, so the continuation runs on any thread pool thread. The code is still bad there: it blocks a thread per request and can starve the thread pool under load.

(c) Fixes

Preferred: async all the way. Event handlers are the one place where async void is correct.

private async void LoadButton_Click(object sender, EventArgs e)
{
    resultBox.Text = await GetDataAsync();
}

Second fix, in library code: do not capture the context.

var response = await _http.GetStringAsync(_url)
    .ConfigureAwait(false);

The continuation then runs on the thread pool, so the blocked UI thread is no longer needed. This is defensive only: it must be applied to every await in the call chain, and the UI still freezes while .Result waits.

Wrapping the call in Task.Run(() => GetDataAsync()).Result also avoids the deadlock, but it still blocks the UI thread. Mention it only as a last resort.

Revise: C# async internals: state machines, ConfigureAwait and ValueTask

Question 2

Q2. Thread safety. This class counts page hits and is registered as a singleton in a web application, so Record is called from many threads at once.

public class HitCounter
{
    private readonly Dictionary<string, int> _hits = new();
    public void Record(string page)
    {
        if (!_hits.ContainsKey(page))
            _hits[page] = 0;
        _hits[page]++;
    }
}

(a) Describe two different things that can go wrong.

(b) A colleague proposes to replace Dictionary with ConcurrentDictionary and keep the method body unchanged. Is that enough?

(c) Write a correct version.

Model answer

(a) Two failures

  • Lost updates. _hits[page]++ is a read, an add and a write. Two threads can both read 5 and both write 6, so one hit disappears. The check then set on the lines above is a race condition too: one thread can reset the count to 0 after another has already counted.
  • Corrupted dictionary. Dictionary is not safe for concurrent writes. A resize during another write can throw, lose entries, or in the worst case leave a thread spinning in an endless loop at 100% CPU.

(b) Not enough. ConcurrentDictionary makes each single call safe, so the structure can no longer be corrupted. But the method is still three separate calls (ContainsKey, set, then get and set for ++), and another thread can run between them. Thread-safe operations do not make a sequence of operations atomic, so hits are still lost.

(c) Correct versions

One atomic operation on a concurrent dictionary:

private readonly ConcurrentDictionary<string, int> _hits
    = new();
public void Record(string page)
{
    _hits.AddOrUpdate(page, 1, (_, count) => count + 1);
}

Or a plain dictionary protected by a private lock object:

private readonly object _gate = new();
private readonly Dictionary<string, int> _hits = new();
public void Record(string page)
{
    lock (_gate)
    {
        _hits.TryGetValue(page, out var count);
        _hits[page] = count + 1;
    }
}
What a strong candidate adds: the update delegate of AddOrUpdate may run more than once under contention, so it must have no side effects. Every reader of the plain dictionary must take the same lock. Lock on a private object, never on this.

Revise: C# concurrency: threads, locks and thread-safe code

Question 3

Q3. Allocation-free parsing. This method is called millions of times per minute with dates such as "2026-11-24", and a profiler shows it creates a lot of garbage.

public static (int Year, int Month, int Day) Parse(string s)
{
    string[] parts = s.Split('-');
    return (int.Parse(parts[0]),
            int.Parse(parts[1]),
            int.Parse(parts[2]));
}

(a) List every heap allocation made by one call.

(b) Rewrite it so that it allocates nothing.

(c) Why can a Span<T> not be stored in a field of a class, and what do you use when you need to?

Model answer

(a) Allocations per call: four. Split allocates one string[] and three new strings ("2026", "11", "24"). The returned tuple is a value type, so it costs nothing on the heap.

(b) Zero-allocation version. A span is a view over the characters of the original string, and int.Parse accepts a ReadOnlySpan<char>.

public static (int Year, int Month, int Day) Parse(string s)
{
    ReadOnlySpan<char> span = s.AsSpan();
    return (int.Parse(span.Slice(0, 4)),
            int.Parse(span.Slice(5, 2)),
            int.Parse(span.Slice(8, 2)));
}

Slice only changes a pointer and a length, so no substring is ever created. If the positions were not fixed, you would find each '-' with span.IndexOf('-') and slice around it.

(c) Why not in a class field. Span<T> is a ref struct. It may point to stack memory (stackalloc) or into the middle of an object, so the runtime must guarantee it never outlives what it points to. The compiler enforces this by keeping it on the stack: it cannot be a field of a class, cannot be boxed, cannot be captured by a lambda, and cannot be kept across an await.

When the reference must live on the heap or cross an await, use Memory<T> or ReadOnlyMemory<T>, and call .Span at the point where you actually read the data.

What a strong candidate adds: measure before and after with BenchmarkDotNet and its memory diagnoser, and use int.TryParse on the spans if the input is not trusted.

Revise: Span, Memory and high-performance C# without allocations

Question 4

Q4. GC generations. Describe the generations of the .NET garbage collector. Why is the heap split this way?

Model answer
  • Gen 0: new objects. Collected very often and very quickly.
  • Gen 1: survivors of one Gen 0 collection. A buffer between short-lived and long-lived objects.
  • Gen 2: long-lived objects. Collected rarely, and a full collection is the expensive one.

The design rests on the observation that most objects die young. Collecting only Gen 0 examines a small region where almost everything is already dead, so few survivors need tracing and copying. An object that survives is promoted to the next generation.

Consequence for code: short-lived temporary objects are cheap; objects that live just long enough to reach Gen 2 and then die (mid-life crisis) are the costly ones.

Question 5

Q5. Large Object Heap. What is the LOH, what goes into it, and what problem can it cause in a long-running service? How do you avoid it?

Model answer
  • Objects of 85,000 bytes or more (in practice large arrays and strings) are allocated on the Large Object Heap.
  • The LOH is collected only with Gen 2, so its objects are expensive to free.
  • By default it is not compacted. Freed blocks leave holes, and after hours of mixed sizes the heap is fragmented: memory use grows although little is live.

Avoid it by not allocating large buffers repeatedly:

  • rent them from ArrayPool<T>.Shared;
  • stream data instead of loading whole files into a byte[];
  • use RecyclableMemoryStream in place of MemoryStream for large payloads.

Question 6

Q6. Finalizers and Dispose. What is the difference between a finalizer and Dispose? Why are finalizers costly, and what does GC.SuppressFinalize(this) do?

Model answer
  • Dispose() is called by your code, at a known time, to release resources now.
  • A finalizer (~MyClass()) is called by the GC, on a dedicated thread, at an unknown time, as a safety net for unmanaged resources.

Cost: an object with a finalizer is not freed when found dead. It is put on a queue, survives that collection, is promoted, and is only freed at a later collection after its finalizer has run. Everything it references survives too.

GC.SuppressFinalize(this), called at the end of Dispose, tells the GC that cleanup is done, so the object is freed normally.

Today you rarely write a finalizer: wrap the handle in a SafeHandle and implement only Dispose.

Question 7

Q7. Managed memory leaks. .NET has a garbage collector. Name four ways a .NET application can still leak memory, and say how you would investigate one in production.

Model answer

A leak in managed code is an object that is still reachable but no longer needed:

  • event handlers never unsubscribed from a long-lived publisher;
  • static collections or caches that only grow;
  • timers and long-running tasks whose callbacks capture objects;
  • closures and lambdas capturing more than intended;
  • undisposed objects holding unmanaged memory.

Investigation:

  1. Watch the trend with dotnet-counters (Gen 2 size, GC heap size).
  2. Take two dumps some time apart with dotnet-gcdump or dotnet-dump.
  3. Compare them: which type keeps growing?
  4. For one instance, look at the path to its GC root (gcroot): that is what keeps it alive.

Question 8

Q8. Workstation and Server GC. What is the difference between Workstation GC and Server GC? What does background (concurrent) GC add?

Model answer
  • Workstation GC: one heap, collection on the triggering thread. Tuned for low memory use and short pauses on a client machine.
  • Server GC: one heap and one dedicated GC thread per core. Collections run in parallel. Much higher throughput, at the price of more memory. Default for ASP.NET Core on multi-core machines.

Background GC lets a Gen 2 collection run mostly at the same time as application threads, so the long pause of a full collection is replaced by short ones. Gen 0 and Gen 1 collections can still happen while it runs.

In containers with small CPU limits, Server GC can use too much memory: this is a common reason to tune GCHeapCount, set DOTNET_gcServer=0, or use the dynamic adaptation mode (DATAS).

Question 9

Q9. Mutable structs. What does this print, and why?

struct Counter
{
    public int N;
    public void Inc() => N++;
}
class Holder
{
    public readonly Counter C = new();
    public void Test()
    {
        C.Inc();
        C.Inc();
        Console.WriteLine(C.N);
    }
}
Model answer

It prints 0.

C is a readonly field of a struct type. The compiler must guarantee the field never changes, but Inc() is not marked as non-mutating. So for each call it makes a defensive copy of the struct and calls Inc() on the copy. The copy is discarded and the field stays at 0. No warning, no error.

Lessons:

  • Avoid mutable structs.
  • Declare structs readonly struct when possible. The compiler then knows no member mutates, and makes no defensive copies, which also matters for in parameters.
  • Mark individual non-mutating members readonly otherwise.

Question 10

Q10. stackalloc. What does Span<byte> buffer = stackalloc byte[256]; do? When is it a good idea and what is the danger?

Model answer

It reserves 256 bytes on the current stack frame, not on the heap. There is no GC allocation, and the memory is released automatically when the method returns. Assigning it to a Span<byte> makes it safe code with bounds checks.

Good for: small, short-lived buffers in a hot path, such as formatting or parsing.

Dangers:

  • The stack is small (about 1 MB by default). A large or user-controlled size causes a StackOverflowException, which cannot be caught and kills the process.
  • Do not use it inside a loop: each iteration takes more stack until the method returns.
Span<byte> buf = size <= 256
    ? stackalloc byte[256]
    : new byte[size];

Question 11

Q11. ArrayPool. Show how to use ArrayPool<byte> correctly and list three mistakes to avoid.

Model answer
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
try
{
    int read = await stream.ReadAsync(buffer.AsMemory(0, 4096));
    Process(buffer.AsSpan(0, read));
}
finally
{
    ArrayPool<byte>.Shared.Return(buffer);
}

Mistakes:

  • Trusting the length. Rent(4096) returns at least 4096 bytes, often more. Always slice to the size you need.
  • Assuming it is zeroed. The array contains data from its previous user. For sensitive data use Return(buffer, clearArray: true).
  • Using it after Return, or returning it twice. Another caller may already own it: this corrupts data silently.
  • Forgetting to return it. Not a leak (the GC still frees it), but the pool no longer helps.

Question 12

Q12. Hidden allocations. A profiler shows many small allocations in a hot method, but there is no new in it. Name five C# constructs that allocate on the heap without an obvious new.

Model answer
  • Boxing: a value type passed as object or as an interface.
  • Closures: a lambda that captures a local variable allocates a closure object and a delegate.
  • params arrays: each call allocates an array for the arguments (unless a span overload exists).
  • LINQ: each operator allocates an iterator, plus delegates.
  • String operations: concatenation, Substring, Split, ToString(), interpolation.
  • Async methods: a state machine is moved to the heap when the method actually suspends, plus a Task.
  • foreach over an interface (IEnumerable<T>): the enumerator is boxed.

Find them with BenchmarkDotNet's [MemoryDiagnoser] or an allocation profiler, and fix only the ones that are measured to matter.

Question 13

Q13. lock. What does the compiler generate for lock (obj) { ... }? Why should you not lock on this, on a Type or on a string?

Model answer
bool taken = false;
try
{
    Monitor.Enter(obj, ref taken);
    // body
}
finally
{
    if (taken) Monitor.Exit(obj);
}

The finally guarantees the lock is released if the body throws.

Never lock on something other code can also reach:

  • this: any caller holding your instance can lock it too.
  • typeof(X): one object shared by the whole process.
  • a string literal: interned, so two unrelated classes locking on "lock" share one lock.

That leads to unexpected contention or deadlocks. Use a private field: private readonly object _gate = new(); From .NET 9, System.Threading.Lock is a dedicated, faster lock type that lock understands.

Question 14

Q14. volatile, Interlocked, lock. Three threads update shared state. Explain what each of volatile, Interlocked and lock guarantees, and which to use for: (a) a stop flag, (b) a counter, (c) updating two related fields.

Model answer
  • volatile: every read sees the latest write (visibility). It does not make compound operations atomic.
  • Interlocked: one atomic operation on one variable (Increment, Add, Exchange, CompareExchange), with no lock.
  • lock: mutual exclusion over a block of code, so any number of operations become atomic together.

Choices:

  • (a) Stop flag: volatile bool, or better a CancellationToken.
  • (b) Counter: Interlocked.Increment(ref _count). volatile with ++ still loses updates.
  • (c) Two related fields: lock. Two separate atomic operations are not atomic as a pair, so another thread could see one updated and not the other.

Question 15

Q15. Lazy initialisation. Is this singleton thread-safe? What is the simplest correct way to write it?

private static Config _instance;
public static Config Instance
{
    get
    {
        if (_instance == null)
            _instance = new Config();
        return _instance;
    }
}
Model answer

Not thread-safe. Two threads can both see null and both create a Config. They may then work with different instances, and an expensive constructor runs twice.

Simplest correct version:

private static readonly Lazy<Config> _instance =
    new(() => new Config());
public static Config Instance => _instance.Value;

Lazy<T> is thread-safe by default: the factory runs once and every thread gets the same value.

Also correct: private static readonly Config _instance = new();, since the runtime guarantees static initialisers run once. Hand-written double-checked locking works only if done exactly right, so prefer Lazy<T>. In an application with dependency injection, register the service as a singleton instead.

Question 16

Q16. Deadlock. Explain how this code can deadlock, and give two ways to prevent it.

void Transfer(Account from, Account to, decimal amount)
{
    lock (from)
    {
        lock (to)
        {
            from.Balance -= amount;
            to.Balance += amount;
        }
    }
}
Model answer

Thread 1 calls Transfer(a, b) and thread 2 calls Transfer(b, a) at the same time:

  • Thread 1 locks a, thread 2 locks b.
  • Thread 1 waits for b, thread 2 waits for a.

Each holds what the other needs: a circular wait, for ever.

Prevention

  1. Lock ordering: always take the locks in the same global order, for example by account id.
var first  = from.Id < to.Id ? from : to;
var second = from.Id < to.Id ? to : from;
lock (first) { lock (second) { /* ... */ } }
  1. Timeout: use Monitor.TryEnter(obj, timeout) and back off if the second lock is not obtained.

Other options: one coarser lock for all transfers, or a design with no shared locks (a single writer processing a queue).

Question 17

Q17. Throttling async work. You must call an API for 1,000 items, but with at most 10 requests in flight at any time. Write it.

Model answer
var gate = new SemaphoreSlim(10);
var tasks = items.Select(async item =>
{
    await gate.WaitAsync();
    try
    {
        return await CallApiAsync(item);
    }
    finally
    {
        gate.Release();
    }
});
var results = await Task.WhenAll(tasks);
  • SemaphoreSlim(10) has 10 permits. WaitAsync waits without blocking a thread.
  • finally returns the permit even if the call fails.
  • lock cannot be used here: await is not allowed inside a lock.

Alternative since .NET 6:

await Parallel.ForEachAsync(items,
    new ParallelOptions { MaxDegreeOfParallelism = 10 },
    async (item, ct) => await CallApiAsync(item, ct));

Question 18

Q18. Reader-writer locks. What problem does ReaderWriterLockSlim solve, and when is it worse than a plain lock?

Model answer

It allows many readers at the same time, or one writer alone. A plain lock lets in one thread at a time, even when all of them only read.

_rw.EnterReadLock();
try { return _cache[key]; }
finally { _rw.ExitReadLock(); }

Better when reads are far more frequent than writes and each read holds the lock for a noticeable time.

Worse when:

  • the protected section is very short: the reader-writer lock has more overhead per entry than lock;
  • writes are frequent, so readers keep being blocked anyway;
  • you need await inside: it has thread affinity and is not async-friendly.

Often a better answer is no lock at all: an immutable snapshot swapped atomically (ImmutableDictionary, or a new dictionary assigned with Interlocked.Exchange), or ConcurrentDictionary.

Question 19

Q19. Channels. What is System.Threading.Channels.Channel<T>? What does a bounded channel give you that an unbounded queue does not?

Model answer

A channel is a thread-safe, async queue for the producer/consumer pattern. Writers call WriteAsync, readers call ReadAsync or ReadAllAsync, and nobody blocks a thread while waiting.

var channel = Channel.CreateBounded<Job>(100);
// producer
await channel.Writer.WriteAsync(job);
channel.Writer.Complete();
// consumer
await foreach (var j in channel.Reader.ReadAllAsync())
    await HandleAsync(j);

A bounded channel has a capacity. When it is full, WriteAsync waits. This is backpressure: a fast producer is slowed to the pace of the consumer, and memory stays bounded.

An unbounded queue accepts everything. If the consumer is slower, it grows until the process runs out of memory. A bounded channel can also be set to drop the oldest or newest item when full.

Question 20

Q20. Parallel work. Compare Parallel.ForEach, Task.WhenAll and Parallel.ForEachAsync. Which do you choose for: (a) resizing 10,000 images in memory, (b) calling 10,000 URLs?

Model answer
  • Parallel.ForEach: runs a synchronous body on several thread pool threads. Made for CPU-bound work. Passing it an async lambda is a bug: it becomes async void and the loop returns before the work is done.
  • Task.WhenAll: waits for tasks that are already started. No limit on concurrency by itself.
  • Parallel.ForEachAsync: runs an async body with a limit on the degree of parallelism.

Choices:

  • (a) Images, CPU-bound: Parallel.ForEach, which uses all cores.
  • (b) URLs, I/O-bound: Parallel.ForEachAsync with MaxDegreeOfParallelism, or WhenAll with a SemaphoreSlim. Starting 10,000 requests at once would exhaust sockets and overload the server.

Question 21

Q21. Async state machine. What does the compiler turn an async method into? When does an async method allocate, and when does it not?

Model answer

The compiler rewrites the method as a state machine: a struct with

  • a field for the current state (which await it is at);
  • fields for the locals and parameters that live across an await;
  • a MoveNext() method containing the original body, cut at each await.

At each await, the awaiter's IsCompleted is checked:

  • Already complete: execution continues synchronously. The state machine stays on the stack. With a cached or value-type result, nothing is allocated.
  • Not complete: the state machine is moved (boxed) to the heap, MoveNext is registered as the continuation, and the method returns its Task to the caller.

So the cost of async is paid when the method really suspends. This is why ValueTask helps on paths that usually complete synchronously.

Question 22

Q22. ValueTask. When should a method return ValueTask<T> and not Task<T>? What must the caller never do with a ValueTask?

Model answer

Use ValueTask<T> when the method often completes synchronously and is called in a hot path: for example a read that usually finds data in a buffer. On that path no Task object is allocated.

If the method almost always suspends, Task<T> is the better default: simpler and no slower.

The caller must never:

  • await it more than once;
  • call .Result or .GetAwaiter().GetResult() before it has completed;
  • use it from several places concurrently.

A ValueTask may wrap a pooled object that is reused after the first await, so a second use reads someone else's result. If you need any of these, convert it first: Task<T> t = valueTask.AsTask();

Question 23

Q23. Exceptions from WhenAll. Three tasks are passed to Task.WhenAll and two of them fail. What does await Task.WhenAll(...) throw? How do you get all the errors? How does .Wait() differ?

Model answer
  • await rethrows only the first exception. The others are not lost, but you do not see them in the catch.
  • All of them are in the task itself:
var all = Task.WhenAll(t1, t2, t3);
try
{
    await all;
}
catch
{
    foreach (var ex in all.Exception!.InnerExceptions)
        _log.Error(ex);
}
  • .Wait() and .Result throw an AggregateException that wraps all of them, and they block the thread.

Also note: WhenAll waits for every task to finish before completing, even when one has already failed. To react to the first failure, use Task.WhenAny in a loop, or cancel the others through a shared CancellationTokenSource.

Question 24

Q24. TaskCompletionSource. An old library exposes void Download(string url, Action<byte[]> onDone, Action<Exception> onError). Wrap it so callers can write await DownloadAsync(url).

Model answer
public Task<byte[]> DownloadAsync(string url)
{
    var tcs = new TaskCompletionSource<byte[]>(
        TaskCreationOptions.RunContinuationsAsynchronously);
    _legacy.Download(url,
        onDone:  data => tcs.TrySetResult(data),
        onError: ex   => tcs.TrySetException(ex));
    return tcs.Task;
}
  • TaskCompletionSource<T> gives you a task you complete by hand with SetResult, SetException or SetCanceled.
  • TrySet... avoids an exception if the library calls back twice.
  • RunContinuationsAsynchronously matters: without it, the code after the caller's await runs inside the library's callback thread, which can cause deadlocks or reentrancy.

No thread is blocked while waiting, unlike wrapping a blocking call in Task.Run.

Question 25

Q25. Async streams. What is IAsyncEnumerable<T> and when is it better than returning Task<List<T>>? Write a method that yields pages of results from an API.

Model answer

IAsyncEnumerable<T> is a sequence whose items arrive asynchronously, consumed with await foreach. It combines yield return with await.

public async IAsyncEnumerable<Order> GetOrdersAsync(
    [EnumeratorCancellation] CancellationToken ct = default)
{
    string? next = "/orders?page=1";
    while (next != null)
    {
        var page = await _api.GetPageAsync(next, ct);
        foreach (var o in page.Items)
            yield return o;
        next = page.NextLink;
    }
}
await foreach (var order in GetOrdersAsync(ct))
    Handle(order);

Better than Task<List<T>> when:

  • the data is large: items are processed as they arrive, memory stays flat;
  • the caller may stop early: the remaining pages are never fetched;
  • the first results should appear quickly.

Question 26

Q26. Reflection. Why is reflection slow, and what are three alternatives when you need dynamic behaviour in a hot path?

Model answer

Why slow: member lookup by name, argument arrays and boxing on each Invoke, security and type checks at run time, and no inlining by the JIT.

Other drawbacks: errors appear only at run time, and it fits badly with trimming and Native AOT, which may remove members that are only reached by reflection.

Alternatives:

  1. Cache the MethodInfo or PropertyInfo once, and reflect only at start-up.
  2. Compile a delegate once and call it many times: MethodInfo.CreateDelegate or a compiled expression tree. Calls then cost about the same as a normal delegate call.
  3. Source generators: generate the code at compile time. No run-time cost and AOT-friendly. Examples: System.Text.Json source generation, [GeneratedRegex], [LoggerMessage].

Generic interfaces and static abstract members also remove many reasons to reflect.

Question 27

Q27. Expression trees. What is the difference between these two declarations, and why does Entity Framework need the second one?

Func<User, bool> f = u => u.Age > 30;
Expression<Func<User, bool>> e = u => u.Age > 30;
Model answer
  • f is a delegate: compiled code. You can only call it.
  • e is an expression tree: a data structure that describes the lambda (a parameter u, a member access Age, a constant 30, a greater-than node). You can inspect it, transform it, or compile it with e.Compile().

Entity Framework cannot look inside a compiled delegate. With the tree, its provider walks the nodes and translates them to SQL: WHERE Age > 30.

That is why IQueryable<T>.Where takes an Expression<Func<T, bool>> and IEnumerable<T>.Where takes a Func<T, bool>. Passing a Func variable to a query silently selects the in-memory overload and loads the whole table.

Limits: only expression lambdas (no statement bodies), and only what the provider knows how to translate.

Question 28

Q28. Variance. (a) Why does IEnumerable<object> x = new List<string>(); compile but List<object> y = new List<string>(); does not? (b) What happens here?

object[] arr = new string[1];
arr[0] = 42;
Model answer

(a) IEnumerable<out T> is covariant: T only comes out of it, so reading strings as objects is always safe.

List<T> is invariant: T goes in (Add) and comes out. If the assignment were allowed, y.Add(42) would put an int into a list of strings. The compiler refuses.

Contravariance is the reverse, with in T: an Action<object> can be used where an Action<string> is expected, because code that accepts any object can accept a string.

Variance works only with interfaces and delegates, and only between reference types.

(b) It compiles, and throws ArrayTypeMismatchException at run time. Arrays are covariant for historical reasons, which is unsafe, so the runtime checks the type on every write to a reference-type array. This is one reason to prefer IReadOnlyList<T> or spans in APIs.

Question 29

Q29. Generics and statics. What does this print? What does it tell you about how the runtime treats generic types?

class Counter<T>
{
    public static int Count;
}
Counter<int>.Count++;
Counter<int>.Count++;
Counter<string>.Count++;
Console.WriteLine(Counter<int>.Count);
Console.WriteLine(Counter<string>.Count);
Model answer

It prints 2 then 1.

Counter<int> and Counter<string> are two different types at run time. Each closed generic type has its own static fields and its own static constructor.

How the JIT compiles them:

  • For each value type argument (int, double, a struct), it generates specialised machine code. No boxing, and calls can be inlined.
  • For all reference type arguments, it shares one copy of the code, since every reference is the same size.

Practical consequences:

  • a static field in a generic class is not shared across type arguments, which surprises people who use it as a global cache;
  • this is also a useful trick: static class Cache<T> { public static readonly X Value = ...; } is a fast per-type cache with no dictionary lookup.

Question 30

Q30. AsyncLocal. You need a correlation id that is available everywhere during one request, including after await. Why does [ThreadStatic] or ThreadLocal<T> not work, and what does?

Model answer

[ThreadStatic] and ThreadLocal<T> store one value per thread. After an await, the method may resume on a different thread pool thread: the value is gone, or worse, you read a value left there by another request.

AsyncLocal<T> stores the value in the execution context, which flows with the async call chain across awaits and into tasks started from it.

static readonly AsyncLocal<string?> CorrelationId = new();
CorrelationId.Value = Guid.NewGuid().ToString();
await DoWorkAsync();          // still visible inside and after

Points to know:

  • The flow is one way: a value set inside a called async method is not visible to the caller after it returns.
  • Store immutable values. A shared mutable object would be seen by all branches.
  • It has a small cost on every async call, so use it for cross-cutting context (correlation id, culture, tenant), not as a replacement for parameters.