C# Interview Questions

Dan Lee's profile image
Dan LeeData & AI Lead
Last update
C# Interview Questions

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.

Software EngineerBackend Engineer.NET DeveloperGame DeveloperFull Stack Engineer

Types, Memory and the Garbage Collector

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 = new List<Point> { new() { X = 1 } };
2// points[0].X = 5;          // CS1612: the indexer returns a copy
3var p = points[0];
4p.X = 5;
5points[0] = p;               // write the modified copy back
6Console.WriteLine(points[0].X); // 5
7
8struct Point { public int X; }
Learn this in the C# and .NET course

LINQ, Collections, Generics and Delegates

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 = new List<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 yet
5Console.WriteLine(evens.Count());  // 2
6Console.WriteLine(evens.Count());  // 2
7Console.WriteLine(calls);          // 8: the source was walked twice
Learn this in the C# and .NET course

async and await

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.

Learn this in the C# and .NET course

Threads, Locks and Concurrent Collections

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 updates
5    Interlocked.Increment(ref safeCount);   // atomic read-modify-write
6});
7Console.WriteLine($"{unsafeCount} vs {safeCount}");  // unsafe is usually below 1000000
Learn this in the C# and .NET course

Modern C# and .NET Application Design

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
1static decimal Shipping(Order o) => o switch
2{
3    { Total: >= 100m }                => 0m,
4    { Country: "US", WeightKg: < 1 }  => 4.99m,
5    { Country: "US" }                 => 9.99m,
6    { Country: not null }             => 24.99m,
7    _ => throw new ArgumentException("Order has no country", nameof(o))
8};
9
10record Order(decimal Total, string? Country, double WeightKg);
Learn this in the C# and .NET course

How to Prepare for C# Interviews

Be able to say where every object lives

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.

Rehearse one concurrency fix per primitive

Have a short example ready for Interlocked, lock, SemaphoreSlim, ConcurrentDictionary with Lazy<T>, and a bounded Channel<T>, and know why each one fits its case. Threads, locks and Interlocked and Concurrent collections and channels build these step by step.

Practice a full coding case under time

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.

Dan Lee's profile image

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.

Connect on LinkedIn