C# and .NET Interview Questions and Answers
C# and .NET interview questions with answers and code: types and memory, OOP, generics, LINQ, async/await, garbage collection, dependency injection, ASP.NET Core and Entity Framework.
Key takeaways
- C# interviews start with value vs reference types, OOP and generics.
- async/await is the most common mid-level topic: deadlocks,
ConfigureAwait,TaskvsValueTask. - Expect LINQ questions, including deferred execution and
IEnumerablevsIQueryable. - Backend roles add ASP.NET Core: middleware, dependency injection lifetimes and EF Core performance.
Contents
C# and .NET interviews test language fundamentals, async programming and the ASP.NET Core / Entity Framework stack. Below are 30 common questions grouped by topic and level, with code.
What C# interviews cover
Editorial estimate.
- Language and OOP25%
- Async and concurrency20%
- LINQ and collections15%
- ASP.NET Core15%
- EF Core and data15%
- Memory and performance10%
Dependency injection lifetimes
| Lifetime | Instance per | Typical use | Pitfall |
|---|---|---|---|
| Transient | Every resolution | Lightweight stateless services | Unnecessary allocations if heavy |
| Scoped | HTTP request | DbContext, unit of work | Injected into a singleton becomes captive |
| Singleton | Application | Caches, configuration, HttpClient factory clients | Must be thread-safe |
Language fundamentals
1Value types vs reference types?
JuniorValue types (int, struct, enum) hold their data directly and are copied on assignment. Reference types (class, string, arrays) hold a reference to an object on the heap, so two variables can point to the same object. Value types usually live inline (on the stack or inside another object).
2class vs struct vs record?
JuniorClasses are reference types with identity. Structs are value types, best for small, immutable data. Records (record class or record struct) provide value-based equality, with expressions and concise syntax for immutable data models.
3What are boxing and unboxing?
JuniorBoxing wraps a value type in an object on the heap (object o = 42;); unboxing extracts it. It costs allocations and time, so generics are preferred over object-based collections.
4What are nullable reference types?
MidA compiler feature that distinguishes string (should never be null) from string? (may be null) and warns about possible null dereferences. It doesn’t change runtime behavior but prevents many NullReferenceExceptions.
5ref vs out vs in parameters?
Juniorref passes a variable by reference that must be initialized; out must be assigned by the method (for example int.TryParse(s, out var n)); in passes by reference as read-only, mainly to avoid copying large structs.
6What is pattern matching in C#?
MidTesting a value against shapes with is and switch expressions:
decimal Discount(Customer c) => c switch
{
{ IsVip: true } => 0.2m,
{ Orders: > 10 } => 0.1m,
_ => 0m
};
OOP and generics
7Abstract class vs interface?
JuniorA class can implement many interfaces but inherit from one class. Interfaces define contracts and may include default implementations; abstract classes can hold state and constructors. Use interfaces for abstractions you inject and mock.
8virtual, override, new and sealed?
Midvirtual allows a method to be overridden; override replaces it in a derived class (polymorphic). new hides the base method, which is resolved by the static type and is usually a smell. sealed prevents further inheritance or overriding.
9What are generic constraints?
MidRestrictions on type parameters, such as where T : class, where T : struct, where T : new() or where T : IComparable<T>, which let you call members of T safely.
10What are covariance and contravariance?
MidCovariance (out T) lets you use a more derived type: an IEnumerable<string> can be used as IEnumerable<object>. Contravariance (in T) lets you use a less derived type: an Action<object> can be used as Action<string>.
Get C# and .NET answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.
LINQ and collections
11What is LINQ?
JuniorLanguage Integrated Query: a consistent way to filter, project, group and join collections and data sources:
var top = orders
.Where(o => o.Status == Status.Paid)
.GroupBy(o => o.CustomerId)
.Select(g => new { Customer = g.Key, Total = g.Sum(o => o.Amount) })
.OrderByDescending(x => x.Total)
.Take(5);
12What is deferred execution in LINQ?
MidMost LINQ operators don’t run until you enumerate the result. Enumerating twice runs the query twice, and the result reflects the source at that moment. Materialize with ToList() when you need a snapshot or will iterate several times.
13IEnumerable vs IQueryable?
MidIEnumerable<T> executes in memory with delegates. IQueryable<T> builds an expression tree that a provider (like Entity Framework) translates to SQL. Calling AsEnumerable() or ToList() too early pulls all rows into memory before filtering.
14List<T> vs Dictionary<TKey, TValue> vs HashSet<T>?
JuniorList for ordered items with index access; Dictionary for O(1) average lookup by key; HashSet for unique items with fast membership checks. Use the concurrent collections when sharing between threads.
Async and concurrency
15How does async/await work?
Midawait on an incomplete task returns control to the caller and schedules the rest of the method as a continuation when the task completes. No thread is blocked while waiting for I/O, which lets servers handle many requests with few threads.
16Why can .Result or .Wait() cause deadlocks?
MidBlocking on a task in a context with a single-threaded synchronization context (classic ASP.NET, UI apps) blocks the thread that the continuation needs, so neither can proceed. Use async all the way down. ASP.NET Core has no synchronization context, but blocking still wastes threads and can cause thread pool starvation.
17What does ConfigureAwait(false) do?
MidIt tells the continuation not to resume on the captured synchronization context. It’s useful in library code to avoid deadlocks and overhead; in ASP.NET Core application code it usually makes no difference.
18Task vs ValueTask?
SeniorValueTask avoids an allocation when a method often completes synchronously (for example a cache hit). It has restrictions: don’t await it more than once or use it concurrently. Use Task by default and ValueTask for measured hot paths.
19How do you cancel async work?
MidPass a CancellationToken through the call chain, check it in long loops (token.ThrowIfCancellationRequested()) and pass it to I/O methods. ASP.NET Core provides HttpContext.RequestAborted when the client disconnects.
20How do you protect shared state between threads?
MidPrefer immutability and concurrent collections (ConcurrentDictionary), use lock for simple critical sections, Interlocked for atomic counters, and SemaphoreSlim for async-friendly limits. You can’t await inside a lock block.
Memory and performance
21How does garbage collection work in .NET?
MidThe GC is generational: new objects start in generation 0, which is collected often; surviving objects move to generations 1 and 2. Large objects (85,000 bytes or more) go to the large object heap. Reducing allocations in hot paths reduces GC pressure.
22What is IDisposable, and how does using work?
MidIDisposable releases unmanaged resources (file handles, connections) deterministically. using calls Dispose automatically, even on exceptions; await using does the same for IAsyncDisposable. Finalizers are a backup for unmanaged resources, not a replacement.
23What are Span<T> and Memory<T> used for?
SeniorViews over contiguous memory (arrays, stack memory, native memory) without copying. They enable high-performance parsing and slicing with fewer allocations. Span<T> is stack-only; Memory<T> can be stored and used across await.
ASP.NET Core
24Explain the ASP.NET Core middleware pipeline.
MidEach request passes through middleware components in registration order (exception handling, HTTPS redirection, routing, authentication, authorization, endpoints). Each can handle the request, modify it, or call the next one. Order matters: authentication must come before authorization.
25What are the dependency injection lifetimes?
MidTransient: a new instance every time. Scoped: one instance per request. Singleton: one instance for the app. Injecting a scoped service (like a DbContext) into a singleton is a classic bug, often called a captive dependency.
26Minimal APIs vs controllers?
MidMinimal APIs define endpoints with lambdas and little ceremony, good for small services. Controllers group actions with attributes, filters and conventions, which suits larger APIs. Both share the same routing, DI and middleware.
27How do you configure settings and secrets?
MidUse the configuration system (appsettings files, environment variables, command line) bound to typed options classes with IOptions<T>. Store secrets in user secrets locally and a vault (Azure Key Vault, AWS Secrets Manager) in production.
Entity Framework Core
28How do you avoid N+1 queries in EF Core?
MidLoad related data explicitly with Include, or project only the fields you need with Select into DTOs. Watch the generated SQL with logging. For large collections, consider split queries (AsSplitQuery).
29What does AsNoTracking do?
MidIt disables change tracking for read-only queries, reducing memory and CPU overhead. Use it for queries whose results you won’t update.
30How do you handle concurrency conflicts in EF Core?
SeniorMark a concurrency token (a rowversion column or a property with [ConcurrencyCheck]). EF includes it in the WHERE clause of updates and throws DbUpdateConcurrencyException when another user changed the row; you then reload, merge or ask the user.
How to prepare
- Master async/awaitContinuations, deadlocks, cancellation, Task vs ValueTask, thread pool starvation.
- Practice LINQ queriesGrouping, joins, projection and deferred execution pitfalls.
- Know DI lifetimes and middleware orderMost ASP.NET Core bugs come from these.
- Review EF Core performanceInclude vs projection, tracking, N+1, generated SQL.
- Prepare a performance storyAllocations, GC pressure or a slow endpoint you fixed.
Get answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.