Top 10 C# scenario questions
Try each one yourself first, then open the model answer.
1. A web request hangs forever when code calls .Result on a task. Why?
Show answerHide answer
Blocking on an async method can deadlock when the continuation needs the blocked context, and it wastes thread pool threads elsewhere. Use await all the way up the call chain.
2. An exception thrown in an async void method crashes the process. How do you fix it?
Show answerHide answer
Callers cannot await or catch async void. Return Task instead, and keep async void only for event handlers, with try/catch inside.
3. A LINQ query runs against the database several times. What is happening?
Show answerHide answer
Queries use deferred execution and run on each enumeration. Materialise once with ToList or ToArray when you need to reuse the results.
4. Loading a page issues hundreds of SQL queries in Entity Framework. How do you solve it?
Show answerHide answer
This is the N+1 problem. Load related data with Include or project only the needed fields with Select, and use AsNoTracking for read-only queries.
5. HttpClient creation per request exhausts sockets. What would you do?
Show answerHide answer
Reuse clients. Use IHttpClientFactory or a long-lived HttpClient with a configured connection lifetime.
6. A singleton service depends on a scoped database context. What goes wrong?
Show answerHide answer
The scoped object is captured for the life of the application, causing stale data and thread-safety errors. Make the consumer scoped, or create a scope inside it with IServiceScopeFactory.
7. Memory grows because objects are never collected after subscribing to events. Why?
Show answerHide answer
The publisher holds a reference to each subscriber. Unsubscribe when done, often in Dispose.
8. You must process a large amount of text with minimal allocations. Which features help?
Show answerHide answer
Use Span and ReadOnlySpan to slice without copying, ArrayPool for buffers, and StringBuilder for building text. Measure with a benchmark before and after.
9. A struct changes in a method but the caller sees no change. Why?
Show answerHide answer
Structs are value types and are copied when passed. Pass by ref, return the new value, or use a class if shared identity is intended. Immutable structs avoid the confusion.
10. A long operation must stop when the user cancels the request. How do you implement it?
Show answerHide answer
Accept a CancellationToken, pass it to every async call, and check it in loops with ThrowIfCancellationRequested.
