C# interviews for backend, game and platform roles rarely ask you to recite syntax. They hand you a snippet that leaks memory, deadlocks under load or quietly queries a whole table, and ask what is going on. The questions test whether you know what the runtime actually does with your code.
Candidates usually slip on the same handful of mechanisms: structs being copied, LINQ queries running more than once, .Result blocking a thread that an await needs, GetOrAdd running its factory twice, and singletons holding scoped services. Each one looks fine in a code review and fails in production.
This page has 31 practice questions in five areas: types and memory, LINQ and collections, async and await, threads and locks, and modern C# with .NET application design. Each answer explains the mechanism and the trap, with runnable C# where code is the clearest proof. Everything reflects C# 14 and .NET 10, the current LTS release.
Intermediate31 questions
C# Interview Questions
Practice C# and .NET interview questions on value types, the garbage collector, LINQ, async/await, concurrency and dependency injection, with worked answers and code.
C# interviews start here because almost every performance or correctness bug traces back to how a value is stored and copied. Interviewers ask about structs, boxing, records and nullable annotations, then push into what the garbage collector does with the objects you allocate.
The idea that matters most: value types copy and reference types share. Once you can say where each object lives, how it is copied and which GC generation will reclaim it, the questions about the large object heap, finalizers and Span<T> follow from that.
Types, Memory and the Garbage Collector
A teammate stores Point structs in a List<Point> and writes points[0].X = 5;. The build fails. Explain the error, fix it, and correct the claim that "structs live on the stack".
EasyTypes, Memory and the Garbage Collector
Sample Answer
The list indexer is a method call that returns a copy of the struct, so assigning to X on that temporary would change nothing. The compiler rejects it with CS1612. Read the element into a local, change it, and write it back. An array is different: arr[0].X = 5 works because array element access yields the storage location itself.
The stack claim is the trap. A value type lives wherever its container lives. A local Point sits on the stack, but the 1,000 Points inside this list sit inline in the list's backing array on the heap. What value types give you is copy semantics, not a memory location. That copying is also why mutable structs are risky and most should be readonly struct.
csharp
1var points =newList<Point>{new(){ X =1}};2// points[0].X = 5; // CS1612: the indexer returns a copy3var p = points[0];4p.X =5;5points[0]= p;// write the modified copy back6Console.WriteLine(points[0].X);// 578structPoint{publicint X;}
You use a small struct GeoKey(double Lat, double Lon, string Region) as a Dictionary key without overriding anything. Lookups are slow and allocate. Why, and what do you change?
MediumTypes, Memory and the Garbage Collector
Sample Answer
Without overrides, the struct falls back to ValueType.Equals(object) and ValueType.GetHashCode. Because it has a reference-type field (Region), the runtime cannot compare raw bits, so it compares field by field through a slow reflection-based path, and the object parameter boxes the struct on every call. The documentation tells you to override Equals especially when a struct holds reference-type fields, and says the default GetHashCode is not likely to be suitable for hash table keys.
The fix is to implement IEquatable<GeoKey> and override GetHashCode, typically with HashCode.Combine(Lat, Lon, Region). The shortest way is readonly record struct GeoKey(...), which generates typed Equals, GetHashCode and == for you. Dictionary uses EqualityComparer<T>.Default, which picks the IEquatable<T> path without boxing.
You copy an order with var b = a with { Id = 2 }; and add an item to b.Items. The original order a now has the item too. Two orders built from identical data also compare unequal. Explain both.
MediumTypes, Memory and the Garbage Collector
Sample Answer
with on a record calls a compiler-generated copy constructor that does a shallow, member-by-member copy. The Items property holds a reference to a List<string>, so a and b now point at the same list, and mutating it through either is visible through both.
Record equality is value-based, but each member is compared with EqualityComparer<T>.Default. For List<string> that is reference equality, so two orders holding different lists with the same contents are unequal.
Fixes: expose an immutable collection (ImmutableArray<string> or IReadOnlyList<string> built once), copy the list explicitly in the with expression, and override Equals(Order?) plus GetHashCode if you need content equality.
csharp
1var a =newOrder(1,["book"]);2var b = a with{ Id =2};3b.Items.Add("pen");4Console.WriteLine(a.Items.Count);// 2: same list5Console.WriteLine(newOrder(1,["x"])==newOrder(1,["x"]));// False67recordOrder(int Id,List<string> Items);
Your service has <Nullable>enable</Nullable> and no warnings, yet production logs a NullReferenceException on a non-nullable string property of a deserialized request. How is that possible?
MediumTypes, Memory and the Garbage Collector
Sample Answer
Nullable reference types are a compile-time analysis. string and string? compile to the same runtime type, and nothing checks for null when values arrive from outside the compiler's view: deserializers, reflection, ORMs, or callers in projects with the feature off. A JSON body that omits the property leaves it null regardless of the annotation.
The ! null-forgiving operator makes it worse, because it silences the warning without adding a check.
Treat annotations as documentation that the compiler enforces inside your code, and validate at the boundary: mark the property required, configure the serializer to respect it, or check with ArgumentNullException.ThrowIfNull (or ArgumentException.ThrowIfNullOrEmpty) in public entry points.
An API that reads uploads into new byte[256 * 1024] per request shows growing memory and frequent gen 2 collections under load. Explain what the GC is doing and how you would fix it.
HardTypes, Memory and the Garbage Collector
Sample Answer
Any object of 85,000 bytes or more is allocated on the large object heap (LOH). The LOH is collected only during generation 2 collections, so these short-lived buffers skip the cheap gen 0 path entirely. Allocating them quickly pushes the GC into frequent full collections. The LOH is also not compacted by default, so freed 256 KB holes fragment it and the process footprint keeps growing.
Fix the allocation pattern rather than tuning the GC. Rent buffers from ArrayPool<byte>.Shared and return them in finally, or stream the body instead of buffering it whole. Rent can return a larger array than requested, so track the length you actually used. GCSettings.LargeObjectHeapCompactionMode exists for one-off compaction, but it treats the symptom.
csharp
1byte[] buffer = ArrayPool<byte>.Shared.Rent(256*1024);2try3{4int read =await body.ReadAtLeastAsync(buffer, buffer.Length,throwOnEndOfStream:false, ct);5Process(buffer.AsSpan(0, read));// use only the bytes you read6}7finally8{9 ArrayPool<byte>.Shared.Return(buffer);10}
A class wraps a native file handle. A reviewer asks for a finalizer "just in case" and you already implement IDisposable. Walk through what a finalizer costs and what the correct pattern is.
MediumTypes, Memory and the Garbage Collector
Sample Answer
An object with a finalizer is registered on the finalization queue when it is allocated. When it becomes unreachable, it is not freed: it moves to a queue served by a single finalizer thread, survives that collection, and is reclaimed only in a later GC. So finalizable objects live longer and get promoted. Finalizers also run in no guaranteed order, and on .NET Core and later they do not run when the process exits.
The modern answer is to wrap the handle in a SafeHandle subclass, which already has a reliable finalizer, and make your class a plain sealedIDisposable that disposes it. If you must write a finalizer, call GC.SuppressFinalize(this) in Dispose so disposed objects skip the queue. Callers use using declarations so disposal happens even on exceptions.
Write a parser for lines like timeout = 30 that returns the key and integer value without allocating any strings. Then explain why you cannot store the result in a field of a class or hold it across an await.
HardTypes, Memory and the Garbage Collector
Sample Answer
ReadOnlySpan<char> is a view over existing memory, so slicing and trimming cost nothing and int.TryParse has a span overload. The method allocates zero bytes.
Span<T> is a ref struct. It can point into the stack (stackalloc) or into the middle of an array, so the compiler restricts it to stack-only lifetimes: it cannot be a field of a class, cannot be boxed or captured by a lambda, and cannot live across an await or yield. Since C# 13, async methods may declare span locals, but those locals still cannot be used after an await. When you need to keep a slice in an object or across an await, use Memory<T> or ReadOnlyMemory<char> and call .Span at the point of use.
LINQ reads like SQL, which is exactly why it causes surprises: queries that run twice, filters that silently run in memory instead of the database, and dictionaries that lose entries. Interviewers use these topics to check whether you know what your code executes, not just what it says.
The key idea is deferred execution. A query is a description until something enumerates it, and the type you hold (IEnumerable<T> or IQueryable<T>) decides whether it runs as C# delegates or gets translated by a provider.
LINQ, Collections, Generics and Delegates
You build var evens = nums.Where(IsEven);, then add an item to nums, then call evens.Count() twice. How many items does each call see and how many times does IsEven run? Why does it matter in production?
EasyLINQ, Collections, Generics and Delegates
Sample Answer
Where is deferred: it returns an iterator that does nothing until something enumerates it. Each Count() enumerates the source from scratch, so both calls see the item added after the query was declared, and the predicate runs once per element per enumeration: 8 calls for 4 items counted twice.
In production the source is often expensive: a database query, a file read, an HTTP stream. Enumerating an IEnumerable<T> twice runs that work twice and can return different results. Materialize once with ToList() or ToArray() when you will enumerate more than once, and keep queries deferred when you will enumerate once. Analyzer rule CA1851 flags possible multiple enumeration.
csharp
1var nums =newList<int>{1,2,3};2int calls =0;3var evens = nums.Where(n =>{ calls++;return n %2==0;});4nums.Add(4);// the query has not run yet5Console.WriteLine(evens.Count());// 26Console.WriteLine(evens.Count());// 27Console.WriteLine(calls);// 8: the source was walked twice
A repository method takes IEnumerable<Order> source and filters with source.Where(o => o.Total > 1000). Callers pass db.Orders from EF Core. The endpoint is slow and memory spikes. What happened?
MediumLINQ, Collections, Generics and Delegates
Sample Answer
Overload resolution is static. Because the parameter type is IEnumerable<Order>, the call binds to Enumerable.Where, which takes a Func<Order, bool> delegate. EF Core cannot translate a compiled delegate, so the whole Orders table is streamed into memory and filtered in C#.
On IQueryable<Order>, Queryable.Where takes an Expression<Func<Order, bool>>, an expression tree the provider translates into a SQL WHERE. Keep the parameter as IQueryable<T> while composing the query, and call ToListAsync once at the end. The same trap appears when someone calls AsEnumerable() too early. Logging the generated SQL makes this visible in seconds.
csharp
1// Translated to SQL: WHERE Total > 10002var big =await db.Orders.Where(o => o.Total >1000).ToListAsync(ct);34// Binds to Enumerable.Where: reads every row, filters in memory5IEnumerable<Order> all = db.Orders;6var slow = all.Where(o => o.Total >1000).ToList();
A Dictionary<Sku, int> reports ContainsKey(key) == false for a key you inserted a moment ago, while Count still includes it. Sku overrides Equals and GetHashCode on its Code property. What went wrong?
MediumLINQ, Collections, Generics and Delegates
Sample Answer
Dictionary<TKey,TValue> is a hash table. On insert it computes GetHashCode() once, stores it in the entry, and links the entry into the bucket chosen by that hash. A lookup recomputes the hash, walks only that bucket, and compares the stored hash before calling Equals.
If code mutates Code after insertion, the key now hashes somewhere else. The lookup searches the wrong bucket, and even a lucky bucket match fails the stored-hash check, so the entry is stranded until the dictionary is rebuilt.
The rule: fields that feed GetHashCode must not change while the object is a key. Make keys immutable (a record or readonly record struct). Lookups average O(1); a terrible hash function degrades them toward O(n).
csharp
1var key =newSku{ Code ="A1"};2var stock =newDictionary<Sku,int>{[key]=10};3key.Code ="B2";// hash changes after insert4Console.WriteLine(stock.ContainsKey(key));// False5Console.WriteLine(stock.Count);// 1: the entry is stranded67classSku8{9publicstring Code {get;set;}="";10publicoverrideboolEquals(object? o)=> o isSku s && s.Code == Code;11publicoverrideintGetHashCode()=> Code.GetHashCode();12}
Write one generic Sum method that works for int, long, double and decimal without boxing, without dynamic, and without a separate overload per type.
HardLINQ, Collections, Generics and Delegates
Sample Answer
Before C# 11 this was impossible: interfaces could not declare operators or static members, so a generic method had no way to say "T supports + and has a zero". C# 11 added static abstract interface members, and .NET 7 shipped generic math on top of them. INumber<T> exposes T.Zero and the + operator, and every built-in numeric type implements it.
The JIT compiles a specialized copy of a generic method for each value-type argument, so Sum<int> runs as tight integer code with no boxing or interface dispatch. The trap answers are where T : struct (gives you no operators) or Convert.ToDouble (loses decimal precision and long range). Taking ReadOnlySpan<T> means arrays and lists both work without copying.
csharp
1usingSystem.Numerics;23staticTSum<T>(ReadOnlySpan<T> values)whereT:INumber<T>4{5T total = T.Zero;6foreach(T v in values) total += v;7return total;8}910Console.WriteLine(Sum<int>([1,2,3]));// 611Console.WriteLine(Sum<decimal>([0.1m,0.2m]));// 0.3
You maintain a public interface IAuditLog with dozens of implementers in other teams. You need to add LogError. How do you do it without breaking them, and what surprises the callers?
MediumLINQ, Collections, Generics and Delegates
Sample Answer
Since C# 8 (on .NET Core 3.0 and later runtimes), an interface member can have a body: a default interface method. Existing implementers compile unchanged and inherit the default, and any of them can override it by implementing the member.
The surprise is that the default is not inherited by the class as a public member. It is reachable only through the interface type. new ConsoleLog().LogError(...) fails with CS1061, while the same call on a variable typed IAuditLog works. Most code holds the interface through DI, so this rarely bites, but tests that use the concrete type do hit it.
Default methods should be written only in terms of other interface members, since they cannot see implementer state.
csharp
1IAuditLog log =newConsoleLog();2log.LogError("disk full");// ERROR disk full3// new ConsoleLog().LogError("x"); // CS1061: not a member of the class45interfaceIAuditLog6{7voidLog(string message);8voidLogError(string message)=>Log("ERROR "+ message);9}10classConsoleLog:IAuditLog{publicvoidLog(string m)=> Console.WriteLine(m);}
A desktop app creates a PriceWidget per open tab and each one subscribes to a long-lived PriceFeed.PriceChanged event. Closed tabs never get collected. Why, and how do you fix it?
EasyLINQ, Collections, Generics and Delegates
Sample Answer
An event is a multicast delegate stored on the publisher, and each delegate holds a reference to its target object. feed.PriceChanged += OnPrice makes the long-lived feed reference the widget, so the widget stays reachable from a GC root for as long as the feed lives. This is the most common managed memory leak.
Unsubscribe when the subscriber's life ends, usually in Dispose. Keep a reference to the handler: unsubscribing a fresh lambda with -= does nothing because it is a different delegate instance, so prefer a method group or a stored delegate. The event keyword also matters for safety: outside code can only += and -=, not invoke the event or overwrite the list with =.
Nearly every .NET service is asynchronous, so interviewers probe the failure modes: deadlocks from blocking on tasks, async void crashes, unbounded fan-out, and cancellation that never reaches the I/O call. Senior loops often hand you buggy async code and ask you to fix it.
Remember that await does not create a thread. It registers a continuation and returns, and the continuation resumes on the captured context if one exists, or on the thread pool. Most async bugs come from blocking, or from losing track of where that continuation runs.
async and await
A teammate writes public async void SaveAsync() and wraps the call in try/catch. When the save throws, the process crashes instead. Explain.
Easyasync and await
Sample Answer
An async void method returns nothing the caller can await, so the caller's try/catch finishes before the exception happens. When the method faults, the exception is raised on the SynchronizationContext that was current when it started. In a console app, a worker or ASP.NET Core there is no context, so it is thrown on a thread pool thread as an unhandled exception and the process terminates.
Use async Task and await it. Reserve async void for event handlers, where the signature is fixed, and catch everything inside the handler. Callers also cannot tell when an async void method finished, which makes such methods hard to test.
Legacy code calls GetDataAsync().Result from a WinForms button handler (or a classic ASP.NET request) and the app hangs forever. Walk through the deadlock and fix it. Does the same code hang in ASP.NET Core?
Mediumasync and await
Sample Answer
.Result blocks the UI thread until the task completes. Inside GetDataAsync, an await captured the current SynchronizationContext and will post its continuation back to the UI thread. The UI thread is blocked waiting for the task, and the task is waiting for the UI thread. Neither moves.
The real fix is async all the way: make the handler async void (an event handler) and await the call. ConfigureAwait(false) inside library code avoids capturing the context, but it only helps if every await in the call chain uses it, so it is not a fix for the caller.
ASP.NET Core has no SynchronizationContext, so it does not deadlock this way. Blocking still burns thread pool threads, and under load that causes thread pool starvation.
A hot path method GetPriceAsync returns a cached value 99% of the time. A profiler shows a Task<decimal> allocation per call. Would you switch to ValueTask<decimal>, and what rules come with it?
Mediumasync and await
Sample Answer
Yes, this is the case ValueTask<TResult> exists for: a method called very often that usually completes synchronously. The struct holds either the result or a task, so the synchronous path allocates nothing. When the method does suspend, the async state machine is still allocated.
The cost is a stricter contract. The documentation says a ValueTask must never be awaited more than once, AsTask must not be called twice, and .Result must not be read before it completes. Consuming it in more than one way gives undefined results, because the backing object may be pooled and reused. If a caller needs to await twice or pass it to Task.WhenAll, call AsTask() once. Task stays the default; switch only when measurements justify it.
An endpoint calls a slow upstream with HttpClient. Add a 2 second timeout that also respects the client disconnecting, and report a timeout differently from a client cancel.
Mediumasync and await
Sample Answer
Link the request's token with a timer: CancellationTokenSource.CreateLinkedTokenSource(requestAborted) cancels when either the client leaves or CancelAfter fires. Pass the linked token into every async call so the upstream request is actually aborted, rather than abandoned while it keeps running.
Cancellation surfaces as OperationCanceledException (or the derived TaskCanceledException). An exception filter on the original token tells the two causes apart. Dispose the linked source with using, since it registers callbacks on the parent token.
The trap: HttpClient.Timeout defaults to 100 seconds and applies to the whole client, so it is the wrong knob for one call. Never swallow the exception when the caller cancelled.
csharp
1asyncTask<string>GetQuoteAsync(HttpClient http,string url,CancellationToken requestAborted)2{3usingvar cts = CancellationTokenSource.CreateLinkedTokenSource(requestAborted);4 cts.CancelAfter(TimeSpan.FromSeconds(2));5try6{7returnawait http.GetStringAsync(url, cts.Token);8}9catch(OperationCanceledException)when(!requestAborted.IsCancellationRequested)10{11thrownewTimeoutException("Upstream did not answer within 2 s");12}13}
You need to call an API for 5,000 URLs. await Task.WhenAll(urls.Select(FetchAsync)) gets you rate-limited and exhausts sockets. Rewrite it so at most 10 requests are in flight.
Hardasync and await
Sample Answer
Select(FetchAsync) starts every task immediately, since calling an async method begins its work, so 5,000 requests go out at once. You need a concurrency limit.
Parallel.ForEachAsync (.NET 6+) takes MaxDegreeOfParallelism and runs at most that many bodies at a time; when you leave it unset, it uses Environment.ProcessorCount, which is a CPU default and rarely right for I/O. Collect results in a ConcurrentDictionary because bodies run concurrently. The older pattern is a SemaphoreSlim(10) with WaitAsync and Release in finally around each call.
Reuse one HttpClient (or IHttpClientFactory) rather than creating one per request, which is the other cause of socket exhaustion.
You run two independent loads with await Task.WhenAll(loadUser, loadOrders) and both fail. Your catch logs only one exception. Where did the other one go, and how do you log both?
Hardasync and await
Sample Answer
Task.WhenAll returns a task that faults with an AggregateException holding every failure. await, however, is designed to feel like synchronous code, so it unwraps and rethrows only the first inner exception. The second one is still recorded on the task.
Keep a reference to the WhenAll task and read task.Exception.InnerExceptions in the catch block. Waiting with .Wait() would surface the full AggregateException, but blocks a thread.
Related detail interviewers like: starting both tasks before awaiting is what makes them concurrent. Writing var u = await LoadUserAsync(); var o = await LoadOrdersAsync(); runs them one after the other, so total latency is the sum instead of the max.
csharp
1Task<User> user =LoadUserAsync(id, ct);// both start now2Task<Order[]> orders =LoadOrdersAsync(id, ct);3Task all = Task.WhenAll(user, orders);4try5{6await all;// rethrows only the first failure7}8catch9{10foreach(var e in all.Exception!.InnerExceptions)11 logger.LogError(e,"Load failed for {Id}", id);12throw;13}
Concurrency questions separate people who have shipped multithreaded services from people who have read about them. Expect lost updates, collections corrupted by concurrent writes, deadlocks and producer/consumer designs, usually framed as a production incident.
Ask what is shared and mutable. If nothing is, you need no synchronization. If one variable is, Interlocked is enough. If several values must change together, you need a lock, and across an await you need an async-friendly primitive such as SemaphoreSlim.
Threads, Locks and Concurrent Collections
Two threads each increment a shared int counter 1,000,000 times with counter++. The final value is around 1.3 million. Explain and fix it with the cheapest correct tool.
EasyThreads, Locks and Concurrent Collections
Sample Answer
counter++ is three steps: read the value, add one, write it back. Two threads can read the same value and both write value + 1, so one increment is lost. Nothing in the language makes ++ on a shared field atomic.
For a single counter, Interlocked.Increment(ref counter) performs the read-modify-write as one atomic CPU instruction, without a lock and without a context switch. Interlocked.Add, Exchange and CompareExchange cover the other single-variable cases.
Use lock when several fields must change together, since Interlocked protects only one memory location. Marking the field volatile does not help here: it affects reordering and visibility, not atomicity of the increment.
csharp
1int unsafeCount =0, safeCount =0;2Parallel.For(0,1_000_000, _ =>3{4 unsafeCount++;// races lose updates5 Interlocked.Increment(ref safeCount);// atomic read-modify-write6});7Console.WriteLine($"{unsafeCount} vs {safeCount}");// unsafe is usually below 1000000
A report cache uses ConcurrentDictionary<string, Report>.GetOrAdd(id, BuildReport). Under load the logs show BuildReport running two or three times for the same id. Isn't ConcurrentDictionary thread-safe?
MediumThreads, Locks and Concurrent Collections
Sample Answer
All its methods are thread-safe, but GetOrAdd is not atomic with respect to the factory. To avoid running unknown code under its internal lock, the dictionary invokes valueFactory outside the lock. Several threads that miss at the same moment each run the factory; one result wins the insert and the rest are discarded. Every caller still gets the same stored value, but the expensive work ran several times.
Wrap the value in Lazy<T>. Creating a Lazy is cheap, only one Lazy instance wins the insert, and its default mode ExecutionAndPublication guarantees the factory inside runs once. For async loaders the same idea uses Lazy<Task<T>>; remember to evict a faulted task or the failure is cached forever.
A singleton uses a plain Dictionary<string, Session> that request threads read and occasionally write. It works in tests, but in production a CPU core pins at 100% and requests hang. What is going on?
MediumThreads, Locks and Concurrent Collections
Sample Answer
Dictionary<TKey,TValue> supports multiple concurrent readers only while nobody modifies it. A write that triggers a resize rebuilds the bucket and entry arrays. A reader or second writer running at the same time can observe half-updated chains, and in practice that produces lost entries, exceptions, or a thread looping forever over a corrupted chain, which matches the pinned core.
Fixes depend on the access pattern. For mixed reads and writes, ConcurrentDictionary gives lock-free reads and fine-grained locked writes. For data written rarely and read constantly, publish a new FrozenDictionary or ImmutableDictionary by swapping a reference. A lock around every access also works but serializes readers. Tests miss this because the race needs real concurrency and a resize at the wrong moment.
You try to refresh an auth token inside lock (_sync) { _token = await FetchTokenAsync(); } and the build fails. Why does C# forbid it, and what do you use instead?
HardThreads, Locks and Concurrent Collections
Sample Answer
A lock is owned by a thread: Monitor.Exit must run on the thread that called Monitor.Enter. After an await, the continuation may run on a different thread pool thread, which could not legally release the lock, and holding a lock during slow I/O blocks threads anyway. The compiler rejects it with CS1996. The .NET 9 System.Threading.Lock type that C# 13 lock statements use is thread-affine too, so it has the same rule.
Use SemaphoreSlim(1, 1) with WaitAsync, which has no thread affinity, and release it in finally. It is not reentrant, so a method that already holds it must not call another method that waits on it. Pass a CancellationToken so waiters can give up.
Transfer(a, b) locks a then b, and Transfer(b, a) locks b then a. Under load the service occasionally freezes. Diagnose it and make transfers deadlock-free.
HardThreads, Locks and Concurrent Collections
Sample Answer
This is the classic lock-ordering deadlock. Thread 1 holds a and waits for b; thread 2 holds b and waits for a. Neither lock is ever released. All four deadlock conditions hold: mutual exclusion, hold-and-wait, no preemption and a circular wait.
Break the cycle by acquiring locks in one global order, for example by account id. Every thread then takes the lower id first, so a circular wait cannot form. Equal ids (a self-transfer) need a guard.
In a dump, dotnet-dump analyze with syncblk shows which threads own which monitors. Monitor.TryEnter with a timeout is a mitigation that turns a hang into an error, not a fix.
An ingestion service reads messages faster than it can write them to the database, and memory climbs until the pod is killed. Design an in-process producer/consumer pipeline with backpressure.
MediumThreads, Locks and Concurrent Collections
Sample Answer
Put a bounded Channel<T> between the reader and the writers. With BoundedChannelOptions(capacity) and FullMode = BoundedChannelFullMode.Wait (the default), WriteAsync waits asynchronously when the channel is full, so the producer slows to the consumer's pace and memory stays capped at roughly capacity times message size. An unbounded channel or a List plus a lock is how the memory leak happens in the first place.
Consumers use await foreach over Reader.ReadAllAsync(ct), which ends cleanly after the producer calls Writer.Complete(). Run several consumer loops for parallel writes. The other full modes (DropOldest, DropNewest, DropWrite) suit telemetry, where losing data beats slowing down.
csharp
1var channel = Channel.CreateBounded<Message>(2newBoundedChannelOptions(1_000){ FullMode = BoundedChannelFullMode.Wait });34asyncTaskProduceAsync(CancellationToken ct)5{6awaitforeach(var msg in source.ReadAllAsync(ct))7await channel.Writer.WriteAsync(msg, ct);// waits when full8 channel.Writer.Complete();9}10asyncTaskConsumeAsync(CancellationToken ct)11{12awaitforeach(var msg in channel.Reader.ReadAllAsync(ct))13await db.SaveAsync(msg, ct);14}
Interviewers want to see that you write current C#, not C# from 2015, and that you understand the .NET host your code runs in. Pattern matching, primary constructors, the C# 14 features in .NET 10, dependency injection lifetimes and exception handling all show up here.
The idea that matters most is lifetime. Who creates an object, who disposes it and how long it lives decides most bugs in this area, from captive DbContext instances to transient services leaking from the root provider.
Modern C# and .NET Application Design
Rewrite a nested if/else shipping-fee function with a switch expression: free over 100 dollars, 4.99 for US orders under 1 kg, 9.99 for other US orders, 24.99 elsewhere, and an error when the country is missing.
EasyModern C# and .NET Application Design
Sample Answer
A switch expression with property patterns and relational patterns states the rules as data. Arms are tried top to bottom, so the most specific rule comes first.
The compiler checks the arms. If an arm can never match because earlier arms cover it, that is error CS8510. If some input is not covered by any arm, you get warning CS8509 and an unmatched input throws SwitchExpressionException at run time. The discard arm _ here makes the switch exhaustive and turns bad data into a clear exception.
Patterns also test null safely: { Country: not null } checks before reading, so no NullReferenceException can come from the property access.
csharp
1staticdecimalShipping(Order o)=> o switch2{3{ Total:>=100m}=>0m,4{ Country:"US",WeightKg:<1}=>4.99m,5{ Country:"US"}=>9.99m,6{ Country:notnull}=>24.99m,7 _ =>thrownewArgumentException("Order has no country",nameof(o))8};910recordOrder(decimal Total,string? Country,double WeightKg);
A class declared as public class RateLimiter(int limit) exposes public int Limit { get; } = limit; and a method that does limit++. After one call, Limit and the effective limit disagree. Explain primary constructor semantics.
MediumModern C# and .NET Application Design
Sample Answer
In a class or struct, a C# 12 primary constructor parameter is a parameter, not a field or property. If a member body uses it, the compiler captures it in a hidden mutable field. Nothing makes that field readonly, so limit++ changes it.
Here the parameter is used twice: once to initialize Limit (a copy taken at construction) and once in a method (the captured field). Those are two separate storage locations, so they drift. The compiler warns with CS9124 for exactly this pattern.
Pick one use: initialize a member and refer only to the member, or use the parameter directly and never copy it. Records differ: positional record parameters generate public properties.
A singleton PriceCache takes ShopDbContext (registered scoped by AddDbContext) in its constructor. In production it throws on concurrent use and serves stale data. Diagnose it and fix the registration.
HardModern C# and .NET Application Design
Sample Answer
This is a captive dependency. A singleton is created once, so the first DbContext it receives lives for the whole process. DbContext is designed for one unit of work and is not thread-safe, so concurrent requests through the singleton throw, and its change tracker keeps returning entities it loaded hours ago.
The default host enables scope validation in the Development environment, which would have failed at startup with "Cannot consume scoped service ... from singleton". Production usually runs without it, which is how this ships.
Fix: inject IServiceScopeFactory and open a scope per unit of work, or use IDbContextFactory<T>. Scope validation does not catch singletons holding stateful transients, so review those by hand.
csharp
1publicsealedclassPriceCache(IServiceScopeFactory scopes)2{3publicasyncTaskRefreshAsync(CancellationToken ct)4{5usingvar scope = scopes.CreateScope();6var db = scope.ServiceProvider.GetRequiredService<ShopDbContext>();7var prices =await db.Prices.AsNoTracking().ToListAsync(ct);8// update the in-memory snapshot here9}10}
Memory in a worker service grows steadily. A heap dump shows thousands of a transient IDisposable class rooted by the service provider. Nobody stores them. How did they get rooted?
MediumModern C# and .NET Application Design
Sample Answer
The built-in container tracks every IDisposable it creates so it can dispose it at the end of the owning scope. For transient services resolved from the root provider, the owning scope is the root, which is disposed only at shutdown. Each resolution adds one more instance to the root's disposal list, so they can never be collected. The DI guidelines document this as a known anti-pattern.
This happens when a background loop or singleton resolves services from IServiceProvider directly instead of from a scope. Fix it by creating a scope per iteration (using var scope = scopeFactory.CreateScope()) or by using a factory and disposing the instance yourself. Avoid registering disposable types as transient where you can.
In a catch block a colleague writes catch (Exception ex) { Log(ex); throw ex; }. During an incident the stack trace points at the catch block, not at the failing line. Explain, and show two correct ways to rethrow.
EasyModern C# and .NET Application Design
Sample Answer
throw ex; throws the existing exception object as if it were new, which resets its stack trace to the current method. The frames that showed where the failure originated are lost.
throw; rethrows the current exception and preserves its original stack trace. If you need to rethrow later, outside the catch block (for example after collecting failures), capture it with ExceptionDispatchInfo.Capture(ex) and call .Throw(), which keeps the original trace. If you want to add context, wrap it: throw new OrderException("...", ex) keeps the original as InnerException.
A related idiom: an exception filter catch (Exception ex) when (Log(ex)) that returns false logs without unwinding the stack at all.
Your team moved to .NET 10. Show how two C# 14 features, the field keyword and null-conditional assignment, simplify a model class and a call site. What exactly runs when customer is null?
MediumModern C# and .NET Application Design
Sample Answer
C# 14 ships with .NET 10, the current LTS release. The field keyword refers to the compiler-generated backing field inside a property accessor, so you can add validation or normalization to one accessor without declaring a private field by hand. If the type already has a member named field, use @field or this.field to mean that member.
Null-conditional assignment allows ?. on the left side of = and compound assignments. customer?.Order = LoadOrder(); evaluates the right side only when customer is not null, so LoadOrder is not even called for a null customer. ++ and -- are not allowed in this form. Other C# 14 additions worth naming are extension members (extension properties and static extensions) and implicit span conversions.
csharp
1publicclassCustomer2{3publicstring Name
4{5get;6set=> field =value?.Trim()??thrownewArgumentNullException(nameof(value));7}="";8publicOrder? Order {get;set;}9}1011customer?.Order =LoadOrder();// LoadOrder runs only if customer is not null
Most C# deep-dive questions reduce to storage and copying. Practice explaining, for any line of code, whether it allocates, what gets copied, and which generation will collect it. Value types and reference types and How the garbage collector works cover the mechanics with measured allocations.
Trace async code by hand
Take a method with three awaits and write down which thread each part runs on, with and without a SynchronizationContext. Then make it deadlock on purpose with .Result. async and await and Async pitfalls and cancellation walk through the state machine and the common failure modes.
Count enumerations and allocations, not lines
For every LINQ answer, say how many times the source is enumerated and whether the query runs in C# or in the database. For hot paths, say how many bytes each call allocates. Deferred execution and iterators and Span, Memory and allocations give you the vocabulary.
Many loops include a build-it round in C#: an LRU cache, a thread-safe cache, or a generic collection. Write one end to end in 45 minutes, including tests and the lifetime of every dependency. Start with Build an LRU cache, then try Build a thread-safe async cache.
How Ready Are You for C# Interviews?
1 / 6
Types
A List<Point> holds mutable structs and points[0].X = 5; fails to compile. What is the best explanation?
Frequently Asked Questions
What C# topics come up most in interviews?
The recurring topics are value versus reference types and boxing, the garbage collector and IDisposable, LINQ and deferred execution, async/await including deadlocks and cancellation, thread safety with locks and concurrent collections, and dependency injection lifetimes in ASP.NET Core. Senior loops add debugging rounds where you read buggy code and explain the failure, plus a design or build exercise such as an LRU cache or a thread-safe cache.
Which C# and .NET version should I prepare for in 2026?
Prepare on .NET 10, the current long-term support release, with C# 14. Most production code you will be asked about still targets .NET 8 or later, so focus on features since C# 8: nullable reference types, records, pattern matching, primary constructors and Span<T>. Knowing a few C# 14 additions, such as the field keyword and extension members, shows you keep current, but interviews rarely depend on them.
How deep do C# interviews go on the garbage collector?
For most backend roles you need generations 0, 1 and 2, the large object heap and its 85,000-byte threshold, why finalizers delay collection, and how managed code still leaks through event handlers, static caches and root-scoped services. Performance-focused roles and game studios go further, into allocation-free code with Span<T>, ArrayPool<T> and stackalloc, and reading GC counters or a heap dump during an incident.
Is async/await the hardest part of C# interviews?
It is the area where experienced candidates lose the most points, because the bugs are subtle. Expect .Result deadlocks, async void crashes, unbounded Task.WhenAll fan-out, swallowed exceptions and cancellation that never reaches the I/O call. Practice tracing which thread runs each continuation and explaining why ASP.NET Core behaves differently from desktop UI frameworks. That one skill answers most async questions.
How long does it take to prepare for a C# interview?
If you write C# daily, two to three weeks of focused practice is usually enough: one area per few days from the list on this page, plus two or three timed coding cases. Coming from Java, plan four to six weeks, since the syntax transfers quickly but structs, async semantics, LINQ and the .NET DI container differ in ways interviewers specifically test.
Do C# interviews include algorithm coding rounds?
Many loops include at least one algorithms round, and you can usually solve it in C#. Know the collection types well: Dictionary, HashSet, PriorityQueue, SortedSet, Queue and Stack, and their complexities. Language-focused loops lean more on practical exercises instead: implementing a generic collection, a cache with eviction, a small class design, or fixing a buggy service.
Written by
Dan Lee
Data & AI Lead
Dan is a seasoned data scientist and ML coach with 10+ years of experience at Google, PayPal, and startups. He has helped candidates land top-paying roles and offers personalized guidance to accelerate your data career.