C# interview questions and answers for .NET developers

C# interview questions check how well you understand the .NET runtime underneath the syntax: value versus reference types, boxing, generics, delegates and events, LINQ deferred execution, and how async/await and Task really behave. Experienced candidates also get records, nullable reference types, pattern matching, IDisposable and memory or deadlock scenarios. Strong answers name the runtime rule and then show a short line of code that proves it.

By Published 9 min read

How C# shows up in developer interviews

C# rounds appear in ASP.NET Core backend roles, enterprise application teams, Unity game studios and desktop work in WPF or WinForms. A typical loop has a language screen with rapid concept questions, a coding exercise in C# (often a small class design or a LINQ-heavy data task), and for experienced hires a discussion of async code, memory and a service they ran in production. Interviewers care less about trivia and more about whether you can predict what the runtime does with your code.

  1. Language screenTen to fifteen short questions: types, boxing, interfaces versus abstract classes, using, LINQ. Answer in two sentences and offer an example.
  2. Coding in C#A small domain model, a parser, or a LINQ query over a list of orders. Readable naming and null handling are graded alongside correctness.
  3. Async and runtimeWhy an app hangs on .Result, what ConfigureAwait(false) changes, how the garbage collector decides what to free.
  4. Design and productionDependency injection lifetimes in ASP.NET Core, a memory leak you diagnosed, how you would structure a service and its tests.

C# fundamentals questions

Core type-system questions for freshers and experienced developers
QuestionWhat it testsWhat a strong answer shows
How do value types differ from reference types?Type systemA struct variable holds the data itself, so assignment copies it. A class variable holds a reference, so two variables can point at one object. Where it lives (stack, heap, inside another object) is a detail of the runtime, not the definition.
What is boxing, and why should you care?AllocationConverting a value type to object or to an interface copies it into a new heap object. In hot loops that means allocations and GC pressure. Generic collections like List<int> exist partly to avoid it.
Why is string immutable, and when do you reach for StringBuilder?StringsImmutability makes strings safe to share and to use as dictionary keys. Concatenating in a loop creates a new string each pass, so a builder is better past a handful of joins.
const versus readonly?Constantsconst is a compile-time value copied into every assembly that uses it, so changing it requires recompiling the callers. readonly is set once at runtime, in a declaration or constructor.
What do ref, out and in mean on a parameter?Parameter passingref passes by reference and must be assigned before the call. out must be assigned by the method. in passes by reference but read-only, useful for large structs.
Abstract class or interface?DesignAn abstract class can hold state and constructors and allows one base. An interface is a contract, and a type can implement many interfaces; since C# 8 it may carry default method bodies, but it still holds no instance fields.
What does sealed buy you?InheritanceNo one can derive from the class. It documents intent and lets the JIT skip virtual dispatch in some calls.
Method overriding versus hiding with new?Polymorphismoverride replaces a virtual method for every caller. new hides it only when the variable's static type is the derived class, which surprises people when a base-typed reference calls the old version.
What is the difference between == and Equals for objects?EqualityFor classes, == compares references unless the type overloads it, as string does. Equals is virtual and can be overridden for value equality. Records generate both for you.
Core type-system questions for freshers and experienced developers. Scroll sideways on a small screen.
var c = new Counter();
object boxed = c;          // copy into a heap object
c.Increment();

Console.WriteLine(c.Value);                // 1
Console.WriteLine(((Counter)boxed).Value); // 0, the box kept the old copy

struct Counter
{
    public int Value;
    public void Increment() => Value++;
}
Boxing copies the struct. The box and the original drift apart.

This snippet is a good way to answer the boxing question without a lecture: the cast back unboxes a second copy, so mutating a struct through an interface or object reference never touches the variable you started with. It is also why mutable structs are discouraged.

Generics, delegates and events

  • Why use generics instead of object parameters? Type safety at compile time, no casts, and no boxing for value types because the runtime creates specialized code for each value type argument.
  • Name some generic constraints and when you need them. where T : class, struct, new(), a base class or an interface. You add one when the method body needs to call something on T, such as CompareTo or a parameterless constructor.
  • What are covariance and contravariance? IEnumerable<out T> lets a sequence of strings be used where a sequence of objects is expected; Action<in T> lets a handler of object stand in for a handler of string. Variance only works on interfaces and delegates, and only for reference types.
  • What is a delegate? A type-safe reference to a method, possibly with a captured target object. Func and Action cover most needs; a custom delegate type is useful when a name documents intent.
  • What does the event keyword add on top of a delegate field? Outside code can only subscribe and unsubscribe with += and -=. Only the declaring class can raise or reset it.
  • How can events cause a memory leak? The publisher holds a reference to every subscriber. A long-lived publisher, such as a static service, keeps short-lived subscribers alive until they unsubscribe.
  • What is a closure over a loop variable, and did foreach change? Lambdas capture variables, not values. Since C# 5 each foreach iteration gets a fresh variable, but a classic for loop still shares one, so lambdas created in it all see the final value.

LINQ and deferred execution

LINQ questions are rarely about syntax. Interviewers want to know when the query actually runs, how many times, and where: in memory or in the database.

var numbers = new List<int> { 1, 2, 3 };
var large = numbers.Where(n => n > 1);   // nothing executes here

numbers.Add(4);
Console.WriteLine(string.Join(",", large)); // 2,3,4

var snapshot = numbers.Where(n => n > 1).ToList(); // runs now
numbers.Add(5);
Console.WriteLine(snapshot.Count);          // 3
A query is a recipe until something enumerates it.
LINQ questions from screen to senior
QuestionWhat it testsWhat a strong answer shows
Which LINQ operators run immediately?Execution modelAnything that must produce a single value or a materialized collection: ToList, ToArray, ToDictionary, Count, First, Sum, Any. Where, Select and OrderBy are deferred.
Why can enumerating a query twice be a bug?Multiple enumerationEach pass re-runs the whole pipeline: a second database round trip, a second file read, or different results if the source changed. Materialize once when you need it twice.
IEnumerable versus IQueryable?Query providersIEnumerable runs delegates in memory. IQueryable builds an expression tree that a provider such as Entity Framework translates to SQL. Calling AsEnumerable too early pulls whole tables into memory.
What is an expression tree?MetaprogrammingCode represented as data. EF reads o => o.Total > 100 as a tree and writes a WHERE clause instead of running the lambda.
How does yield return work?IteratorsThe compiler builds a state machine; the method body runs lazily, one element per MoveNext. Argument checks inside it are also deferred, which is why validation often sits in a wrapper method.
First versus FirstOrDefault versus Single?IntentFirst throws on empty, FirstOrDefault returns default, Single also throws when more than one item matches. Single documents that duplicates are a data error.
LINQ questions from screen to senior. Scroll sideways on a small screen.

Async/await and Task questions

Async is where most experienced C# candidates are separated. Know that await frees the thread rather than creating one, that the continuation resumes on the captured context when there is one, and that blocking on async work is the classic way to deadlock a UI app.

private void OnSaveClicked(object sender, RoutedEventArgs e)
{
    // Blocks the UI thread until LoadAsync finishes...
    var text = LoadAsync().Result;
}

private async Task<string> LoadAsync()
{
    await Task.Delay(100);
    // ...but this line wants to resume on the UI thread, which is blocked.
    return "done";
}
The classic deadlock in a WPF or WinForms handler.

The fix is to make the handler async and await the call. ConfigureAwait(false) inside library code also avoids the trap, because the continuation no longer needs the UI context. ASP.NET Core has no synchronization context, so the same code does not deadlock there, but blocking still wastes a thread-pool thread.

  • Does async mean multithreaded? No. An awaited I/O call uses no thread while it waits. Parallel CPU work is a separate tool: Task.Run, Parallel.ForEach or PLINQ.
  • Task.Run versus new Thread? Task.Run queues work on the thread pool and returns a Task you can await and compose. A dedicated Thread suits long-running work with special needs, such as a custom priority.
  • Why avoid async void? The caller cannot await it, and an exception escapes to the synchronization context, often crashing the process. Keep it for event handlers only.
  • How does cancellation work? Pass a CancellationToken down the call chain, check it or hand it to APIs that accept one, and let them throw OperationCanceledException. Cancellation is cooperative; nothing is killed.
  • When is ValueTask worth it? When a method usually completes synchronously, such as a cache hit, and allocation matters. It must be awaited only once, so it is not a free upgrade.
  • How do you run three independent calls at once? Start all three, then await Task.WhenAll. Awaiting them one by one serializes the waits.
  • What protects shared state in async code? lock cannot contain an await. Use SemaphoreSlim with WaitAsync, or redesign so each piece of state has one owner, for example a Channel.

Memory, IDisposable and the garbage collector

Runtime questions for mid-level and senior roles
QuestionWhat it testsWhat a strong answer shows
How does the .NET GC decide what to collect?Generational GCObjects start in generation 0; survivors are promoted to 1 and 2. Most objects die young, so collecting gen 0 often is cheap. Large objects go on a separate heap that is collected with gen 2.
Dispose versus a finalizer?Resource cleanupDispose releases resources deterministically when your code says so. A finalizer is a safety net the GC runs later and only for unmanaged handles. Most classes need Dispose and no finalizer at all.
What does a using statement compile to?Language sugarA try/finally that calls Dispose. The using var declaration form disposes at the end of the enclosing scope. await using calls DisposeAsync.
Why does an HttpClient per request cause trouble?SocketsDisposing it does not free the socket right away, so a busy service can run out of ports. Reuse instances or use IHttpClientFactory.
What is Span<T> for?Allocation-free codeA view over contiguous memory, such as a slice of an array or a stack buffer, with no copy. It is a ref struct, so it cannot be boxed, stored in a field of a class or captured across an await.
A service's memory keeps climbing. What do you do?DiagnosticsWatch the GC counters, take two heap dumps some time apart and compare which types grew. Usual suspects: static caches without eviction, event subscriptions never removed, and captured closures.
Runtime questions for mid-level and senior roles. Scroll sideways on a small screen.

Modern C#: records, nullable references and pattern matching

var a = new Point(1, 2);
var b = a with { Y = 5 };

Console.WriteLine(a == new Point(1, 2)); // True: compares X and Y
Console.WriteLine(b);                    // Point { X = 1, Y = 5 }

public record Point(int X, int Y);
Records give value equality, a readable ToString and non-destructive copies.
static decimal ShippingFee(Order o) => o switch
{
    { Total: >= 500m }               => 0m,
    { Express: true, Country: "US" } => 15m,
    { Express: true }                => 25m,
    null                             => throw new ArgumentNullException(nameof(o)),
    _                                => 5m,
};
A switch expression with property and relational patterns.
  • Record or class? Records fit data that is defined by its values: DTOs, messages, events, keys. Classes fit objects with identity and behavior that changes over time. A record struct gives the same features on a value type.
  • Are records immutable? Positional records get init-only properties, so they are shallowly immutable. A list property inside one can still be changed.
  • What do nullable reference types change at runtime? Nothing. They are compiler annotations and warnings. A string parameter can still receive null from older code, so public APIs keep their null checks.
  • What is the `!` operator? The null-forgiving operator tells the compiler you know a value is not null. Overusing it hides the bugs the feature exists to find.
  • How would you turn on nullable references in a large legacy project? File by file or project by project with #nullable enable, fixing warnings at the edges first, and treating new warnings as errors once a module is clean.
  • Why does the order of switch arms matter? Arms are tested top to bottom, so put specific patterns before general ones. The compiler flags an arm that can never match.

Senior and scenario questions

Scenarios for experienced .NET developers
ScenarioWhat it testsWhat a strong answer shows
A scoped DbContext is injected into a singleton.DI lifetimesA captive dependency: one context lives for the whole app and is shared across requests, which is not thread-safe. Inject a factory or create a scope per unit of work.
An API endpoint is slow under load but fast alone.Thread-pool starvationLook for sync-over-async calls such as .Result or .Wait() that block pool threads. The fix is async all the way down, not a bigger pool.
A report query loads ten thousand rows to show twenty.IQueryable misuseFiltering and paging happen after ToList. Move Where, OrderBy, Skip and Take before materializing and check the generated SQL.
You need to share a cache across threads.ConcurrencyConcurrentDictionary with GetOrAdd, aware that the value factory may run more than once; Lazy<T> values when it must run once.
How would you test a class that calls DateTime.Now?TestabilityInject a clock abstraction such as TimeProvider in recent .NET versions, or your own interface, so tests control time.
Scenarios for experienced .NET developers. Scroll sideways on a small screen.

Fictional example

Answering "Tell me about a production issue you fixed in .NET"
Our order API started timing out every Monday morning, when traffic peaked. CPU was low, which pointed away from heavy computation. A dump showed hundreds of thread-pool threads parked inside a payment client that wrapped an async call with .Result. Under load, each blocked thread forced the pool to grow slowly while requests queued behind it. I made the client and its callers async end to end, passed the request's CancellationToken through, and added an analyzer rule that flags blocking calls on tasks. Latency at the Monday peak went back to its weekday level, and we added a load test that runs before each release so the pattern cannot sneak back.

Two-week C# preparation plan

  • Days 1 to 3: types, boxing, equality, strings and parameter passing. Write a five-line console program for each answer and predict the output first.
  • Days 4 to 6: generics, variance, delegates, events and closures. Explain each in under a minute, out loud.
  • Days 7 to 9: LINQ. Rewrite three loops as queries, mark which operators are deferred, and read the SQL that EF Core generates for one of them.
  • Days 10 to 12: async. Reproduce the .Result deadlock in a small WPF or WinForms app, fix it, then add cancellation and Task.WhenAll.
  • Days 13 and 14: a timed exercise: build a small domain model with records and pattern matching, add tests, and review your own code for disposal and null handling.

C# shares a lot of ground with other managed and systems languages. For memory and object lifetime from the other side, compare with C++ interview questions; for a JVM language with similar null-safety ideas, see Kotlin interview questions. The wider role view is in backend developer interview questions.

Explaining a deadlock or a GC generation aloud is harder than reading about it, so rehearse it. Natively, an AI interview assistant for Mac and Windows, transcribes a mock .NET interview so you can reread where an async explanation went vague. During practice it can read a C# problem from a screenshot, suggest an approach or a hint, and, with Pro or the free trial, use the résumé and job description you add to shape the answers. The transcript and notes stay available to review afterward.

Questions people ask

What C# questions are asked in interviews?

Expect value versus reference types and boxing, interfaces versus abstract classes, generics, delegates and events, LINQ deferred execution, and async/await with Task. Experienced roles add IDisposable and the garbage collector, records, nullable reference types and pattern matching.

How do I prepare for a C# developer interview?

Write a tiny console program for each concept and predict its output before you run it. Then practice explaining the .Result deadlock, LINQ deferred execution and DI lifetimes out loud, and do one timed exercise that builds a small domain model with tests.

What are advanced C# interview questions?

Senior rounds ask about sync-over-async and thread-pool starvation, captive dependencies in ASP.NET Core, IQueryable versus IEnumerable, Span<T>, variance, and how you found a memory leak with heap dumps.

Do C# interviews include a coding round?

Usually. Common tasks are a small class design, a LINQ query over a collection, a parser, or refactoring blocking code to async. Readability, null handling and tests are judged along with correctness.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP