Skip to content

Hard .NET Full Stack Interview Questions

43 hard questions with answers. Design, trade-off and deep-dive questions asked for senior roles and at top product companies.

Topics in the hard set

Entity Framework Core: 9 Async Programming and Multithreading: 8 SQL Server and T-SQL: 6 LINQ, Collections and Generics: 5 ASP.NET Core Web API: 5 C# Fundamentals: 4 OOP in C#: 3 Angular and React Front End: 3
Solved — hardStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

How does garbage collection work in .NET and what are generations?

Save to ▾
Show answer
The GC automatically frees objects that are no longer reachable from roots such as static fields, locals and CPU registers. The heap is split into generations: Gen 0 for new short-lived objects, Gen 1 as a buffer, and Gen 2 for long-lived objects. Most objects die young, so Gen 0 collections are frequent and cheap. Objects over 85,000 bytes go to the Large Object Heap, which is collected with Gen 2.
02

What are Span<T> and Memory<T> and why do they matter for performance?

Save to ▾
Show answer
Span<T> is a ref struct that represents a contiguous slice of memory, such as part of an array, a string or stack memory, without copying it. Slicing a span is free, which makes parsing much faster with zero allocations. Because it is stack-only, it cannot be stored in fields or used across await. Memory<T> is the heap-storable version for async code. ASP.NET Core and System.Text.Json use them heavily.
03

A .NET API's memory keeps growing in production until the pod restarts. How do you investigate?

Save to ▾
Show answer
First confirm with metrics using dotnet-counters: watch GC heap size, Gen 2 count and LOH size. Then capture a heap dump with dotnet-gcdump or dotnet-dump and compare two dumps over time to find which object types keep growing and what roots hold them. Common causes are static caches without expiry, event handlers never unsubscribed, undisposed HttpClient or DbContext, and singletons capturing scoped services. Fix the root, then load test.
04

What is the difference between JIT compilation and Native AOT in .NET?

Save to ▾
Show answer
With JIT, the app ships as IL and the runtime compiles methods to machine code when first called; tiered compilation later recompiles hot methods with better optimisation. Native AOT compiles everything ahead of time into a single native executable, giving very fast startup and lower memory, which suits containers and serverless. The trade-off is limited reflection and dynamic code generation, so some libraries need source generators to work.
05

A PaymentService has a large if-else on payment type (card, UPI, netbanking, wallet) and every new method means editing it. How do you refactor?

Save to ▾
Show answer
Apply the Strategy pattern with the Open/Closed principle. Define IPaymentProcessor with a Type property and ProcessAsync method, and create one class per method. Register all of them in DI, inject IEnumerable<IPaymentProcessor>, and pick the right one by type, possibly through a dictionary. Adding a new payment type is now a new class plus a registration, with no change to existing, tested code.
06

Write a thread-safe singleton in C#.

Save to ▾
Show answer
public sealed class AppConfig { private static readonly Lazy<AppConfig> _instance = new(() => new AppConfig()); public static AppConfig Instance => _instance.Value; private AppConfig() { // load settings once } } Lazy<T> is thread-safe by default and creates the object only on first access. The private constructor and sealed class prevent other instances. In ASP.NET Core, prefer AddSingleton.
07

Give an example of a Liskov Substitution Principle violation and how to fix it.

Save to ▾
Show answer
A classic case is Square inheriting Rectangle. Setting Width on a square also changes Height, so code that sets width 5 and height 4 and expects area 20 breaks. Another real case is a ReadOnlyRepository that inherits Repository and throws NotSupportedException on Save. The fix is to model shared behaviour with interfaces such as IShape or IReadRepository and IWriteRepository, so subclasses never weaken the contract.
08

How does Dictionary<TKey, TValue> work internally?

Save to ▾
Show answer
Dictionary is a hash table. It calls GetHashCode on the key to choose a bucket, then uses Equals to find the exact entry if several keys share a bucket. Lookups, inserts and deletes are O(1) on average. When it fills up, it resizes and rehashes. Keys must have stable hash codes, so never mutate a key object after inserting it, and override GetHashCode with Equals for custom key types.
09

Explain covariance and contravariance in C# generics.

Save to ▾
Show answer
Covariance, marked out T, lets you use a more derived type where a base type is expected: IEnumerable<string> can be assigned to IEnumerable<object> because the interface only returns T. Contravariance, marked in T, allows the reverse for inputs: an Action<object> can be used as Action<string>. They apply only to interfaces and delegates, and only with reference types. List<T> is invariant because it both reads and writes T.
10

Several threads update an in-memory Dictionary cache in a singleton service and you see corrupted data and exceptions. What would you use instead?

Save to ▾
Show answer
System.Collections.Concurrent provides thread-safe collections: ConcurrentDictionary, ConcurrentQueue, ConcurrentStack, ConcurrentBag and BlockingCollection. They use fine-grained locking or lock-free techniques, so multiple threads can read and write without your own lock. Use ConcurrentDictionary for in-memory caches in singleton services. Note that GetOrAdd may run the value factory more than once under contention, so keep the factory side-effect free or wrap it in Lazy<T>.
11

You load 5,000 pincode-to-city mappings at startup and read them millions of times a day from many threads. Which collection would you use?

Save to ▾
Show answer
Immutable collections like ImmutableList and ImmutableDictionary never change; modifications return a new collection that shares structure, which makes them safe to share across threads. FrozenDictionary and FrozenSet, added in .NET 8, are built once and heavily optimised for fast reads but cannot be modified. They suit lookup tables loaded at startup, such as state codes or feature flags, read millions of times per day.
12

An API endpoint calls _db.Orders.ToList().Where(o => o.CustomerId == id) and is slow as the table grows. Explain and fix it.

Save to ▾
Show answer
ToList executes immediately, so the entire Orders table is loaded into memory and then filtered in C#. As data grows, memory and response time grow with it. Move the filter before materialisation: await _db.Orders.Where(o => o.CustomerId == id).AsNoTracking().ToListAsync(). Now EF Core sends a WHERE clause, the database uses an index on CustomerId, and only matching rows travel over the network.
13

A legacy ASP.NET MVC app on .NET Framework hangs when a controller calls GetDataAsync().Result. Why, and how do you fix it?

Save to ▾
Show answer
This is the classic sync-over-async deadlock. .Result blocks the request thread, which holds the ASP.NET synchronization context. When the awaited task completes, its continuation tries to resume on that same context, which is blocked, so neither can proceed. The real fix is async all the way: make the action async and await the call. Where that is impossible, ConfigureAwait(false) inside the library avoids capturing the context.
14

What does ConfigureAwait(false) do and is it needed in ASP.NET Core?

Save to ▾
Show answer
By default await captures the current SynchronizationContext and resumes on it. ConfigureAwait(false) tells the runtime it can resume on any thread pool thread, which avoids deadlocks in UI and old ASP.NET apps and slightly reduces overhead. ASP.NET Core has no SynchronizationContext, so it is not required in application code there. It is still recommended in general-purpose libraries that might be used by WPF or WinForms apps.
15

Profiling shows a hot cache-lookup method returning Task<T> allocates millions of Task objects. Would ValueTask help?

Save to ▾
Show answer
ValueTask<T> is a struct that avoids allocating a Task when a method usually completes synchronously, for example when a value is served from an in-memory cache most of the time. In very hot paths this reduces GC pressure. The rules are stricter: await a ValueTask only once, do not await it concurrently, and do not call .Result before it completes. For normal application code, Task is simpler and recommended.
16

Limit concurrent calls to a third-party API to 5 at a time using SemaphoreSlim.

Save to ▾
Show answer
private static readonly SemaphoreSlim _gate = new(5); public async Task<string> CallAsync(string url) { await _gate.WaitAsync(); try { return await _http.GetStringAsync(url); } finally { _gate.Release(); } } var results = await Task.WhenAll(urls.Select(CallAsync)); SemaphoreSlim supports async waiting, unlike lock. The finally block guarantees the slot is released even when a call fails.
17

Under load, an API's response time jumps to many seconds while CPU stays low. Thread count keeps rising. What is likely happening?

Save to ▾
Show answer
This pattern points to thread pool starvation. Some code is blocking threads with .Result, .Wait(), Thread.Sleep or synchronous I/O, so pool threads are stuck waiting and the pool injects new threads slowly. Confirm with dotnet-counters, watching thread pool queue length and thread count, and a dump showing many threads blocked in Wait. Fix by making the call chain fully async; raising minimum threads is only a temporary patch.
18

What are System.Threading.Channels and when would you use them?

Save to ▾
Show answer
Channels provide fast, thread-safe, async producer-consumer queues. A producer writes with await writer.WriteAsync and a consumer reads with await foreach over reader.ReadAllAsync. Bounded channels apply back-pressure by making producers wait when full. They are useful inside one process, for example an API that accepts uploads quickly and hands them to a background worker. For durable or cross-service queues use a broker like RabbitMQ or Azure Service Bus.
19

How are exceptions handled in async code, and what is AggregateException?

Save to ▾
Show answer
When you await a faulted task, the original exception is rethrown, so normal try-catch works. If you block with .Wait() or .Result, the exception is wrapped in AggregateException. With Task.WhenAll, await throws only the first exception, but the returned task's Exception property holds all of them in an AggregateException. Unobserved exceptions from fire-and-forget tasks are silently lost, so always await or log them.
20

What is a SynchronizationContext?

Save to ▾
Show answer
A SynchronizationContext represents where continuations should run. WPF and WinForms have one that marshals work back to the UI thread, so after await you can update controls safely. Classic ASP.NET had one tied to the request. ASP.NET Core and console apps have none, so continuations run on any thread pool thread. Understanding it explains why .Result deadlocks in UI apps but often not in ASP.NET Core.
21

A singleton CacheService injects AppDbContext, and users start seeing stale data and occasional 'a second operation was started on this context' errors. What is wrong?

Save to ▾
Show answer
This is a captive dependency: a scoped DbContext is captured by a singleton, so one context lives forever and is shared by all requests across threads. DbContext is not thread-safe and its change tracker grows stale. Fix it by injecting IServiceScopeFactory or IDbContextFactory<AppDbContext> into the singleton and creating a short-lived context per operation. Enabling ValidateScopes in development catches this at startup.
22

Your product API runs on four instances behind a load balancer and needs caching. Which ASP.NET Core caching options would you consider?

Save to ▾
Show answer
IMemoryCache stores data in the server's memory, fast but not shared across instances. IDistributedCache uses Redis or SQL Server so all instances share the cache. HybridCache, added in .NET 9, combines an in-memory layer with a distributed one and prevents cache stampedes. Output caching stores whole HTTP responses on the server, while response caching sets HTTP headers for browsers and proxies. Always set expiry and invalidate when data changes.
23

Add rate limiting to a login endpoint in ASP.NET Core.

Save to ▾
Show answer
builder.Services.AddRateLimiter(o => { o.RejectionStatusCode = StatusCodes.Status429TooManyRequests; o.AddPolicy("login", ctx => RateLimitPartition.GetFixedWindowLimiter( ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) })); }); app.UseRateLimiter(); app.MapPost("/api/login", LoginHandler).RequireRateLimiting("login"); Each IP gets 5 attempts per minute, which slows brute-force attacks. Behind a proxy, use the forwarded client IP.
24

Your product API must handle a festive sale with 10 times normal traffic. How do you prepare it?

Save to ▾
Show answer
Make the API stateless so you can scale it horizontally behind a load balancer or Kubernetes autoscaler. Cache read-heavy data such as product details in Redis or HybridCache. Ensure all I/O is async and database queries are indexed, projected and paged. Move slow work like emails to queues. Add rate limiting, timeouts and circuit breakers to dependencies, then load test with k6 or JMeter and watch metrics.
25

Access tokens in your app expire in 15 minutes and users complain about being logged out. How do you implement refresh tokens securely?

Save to ▾
Show answer
Issue a short-lived JWT access token plus a long-lived, random refresh token stored hashed in the database with expiry and device info. When the access token expires, the client calls /refresh with the refresh token; the server validates it, revokes it and issues a new pair, which is rotation. Reuse of a revoked token signals theft, so revoke the whole chain. In browsers, store the refresh token in an HttpOnly, Secure, SameSite cookie.
26

How does change tracking work and what are entity states?

Save to ▾
Show answer
The change tracker keeps a snapshot of each tracked entity and compares it on SaveChanges. Each entity has a state: Added (insert), Modified (update), Deleted (delete), Unchanged (no action) and Detached (not tracked). Calling Add, Update or Remove sets states, and changing a property of a tracked entity marks it Modified. SaveChanges then generates SQL only for changed columns, all inside one transaction.
27

Two support agents edit the same customer record at once and one agent's changes silently overwrite the other's. How do you prevent this?

Save to ▾
Show answer
Use optimistic concurrency. Add a [Timestamp] byte[] RowVersion property, which maps to SQL Server rowversion. EF Core includes it in the WHERE clause of updates; if another user changed the row, zero rows are affected and DbUpdateConcurrencyException is thrown. Catch it, reload current values and show the agent a conflict message or merge screen. This avoids locking rows while users are editing on screen.
28

Implement soft delete with a global query filter.

Save to ▾
Show answer
public class Product { public int Id { get; set; } public bool IsDeleted { get; set; } } protected override void OnModelCreating(ModelBuilder mb) { mb.Entity<Product>().HasQueryFilter(p => !p.IsDeleted); } public override Task<int> SaveChangesAsync(CancellationToken ct = default) { foreach (var e in ChangeTracker.Entries<Product>().Where(e => e.State == EntityState.Deleted)) { e.State = EntityState.Modified; e.Entity.IsDeleted = true; } return base.SaveChangesAsync(ct); } Every query now hides deleted rows automatically; use IgnoreQueryFilters() for admin screens.
29

What techniques improve EF Core query performance?

Save to ▾
Show answer
Project only needed columns with Select instead of loading full entities. Use AsNoTracking for reads. Avoid N+1 with Include or projections. Page with Skip and Take or keyset paging. Add proper indexes via HasIndex. Use ExecuteUpdate and ExecuteDelete for bulk changes. For hot queries, compiled queries with EF.CompileAsyncQuery and DbContext pooling with AddDbContextPool reduce overhead. Always check generated SQL with logging or ToQueryString.
30

An EF Core query that includes Items and Payments for each order returns a huge, duplicated result set. What is happening and how do split queries help?

Save to ▾
Show answer
When you Include two or more collection navigations, such as Orders with Items and Payments, EF Core generates one query with joins. Rows multiply: 10 items times 5 payments return 50 rows per order, duplicating data heavily. AsSplitQuery() tells EF Core to run separate queries per collection and stitch results together, avoiding duplication. The trade-off is more round trips and possible inconsistency without a transaction.
31

Your team debates wrapping EF Core in a generic repository. What is your view?

Save to ▾
Show answer
DbContext already implements Repository and Unit of Work, so a thin generic repository with GetAll and Add often adds code while hiding useful features like Include, projections and AsNoTracking. I prefer either using DbContext directly in services, or specific repositories with meaningful methods like GetOverdueInvoicesAsync that encapsulate queries. For tests, use the SQLite in-memory provider or Testcontainers rather than mocking DbSet.
32

A complex reporting query written in EF Core is slow and hard to tune. When would you move it to Dapper?

Save to ▾
Show answer
Dapper is a micro-ORM that maps raw SQL results to objects with very low overhead. It suits read-heavy reports, complex hand-tuned queries and stored procedures where you want full SQL control. EF Core offers change tracking, migrations, LINQ and relationships, which speed up CRUD development. Many projects use both: EF Core for writes and normal features, Dapper for performance-critical queries, sharing the same connection string.
33

You must rename a column and split a Name field into FirstName and LastName in a production database with live data. How do you deploy safely?

Save to ▾
Show answer
Avoid destructive one-step migrations. Use an expand-and-contract approach: first add new nullable columns, deploy code that writes both old and new, and backfill data with a script in batches. Then switch reads to the new columns, and only in a later release drop the old column. Generate idempotent SQL scripts, review them with the DBA, take a backup and test on a production copy first.
34

Your multi-tenant SaaS app keeps all tenants in one database. How do you make sure EF Core queries never return another tenant's data?

Save to ▾
Show answer
Add a TenantId column to every tenant-owned entity and a global query filter such as HasQueryFilter(e => e.TenantId == _tenantId), where the tenant ID comes from a scoped provider that reads the authenticated user's claim. Set TenantId automatically in SaveChanges for new rows. Index TenantId, write integration tests that try cross-tenant access, audit every IgnoreQueryFilters call, and consider SQL Server row-level security as a second layer of defence.
35

Write a recursive CTE that lists an employee hierarchy with levels.

Save to ▾
Show answer
WITH Org AS ( SELECT Id, Name, ManagerId, 0 AS Lvl FROM Employees WHERE ManagerId IS NULL -- anchor: CEO UNION ALL SELECT e.Id, e.Name, e.ManagerId, o.Lvl + 1 FROM Employees e JOIN Org o ON e.ManagerId = o.Id -- recursive part ) SELECT REPLICATE(' ', Lvl) + Name AS Hierarchy, Lvl FROM Org OPTION (MAXRECURSION 100); The anchor query runs once and the recursive part repeats until no new rows are found.
36

What are ACID properties and the transaction isolation levels in SQL Server?

Save to ▾
Show answer
ACID means Atomicity (all or nothing), Consistency (rules hold), Isolation (transactions do not interfere) and Durability (committed data survives crashes). Isolation levels are READ UNCOMMITTED (dirty reads allowed), READ COMMITTED (the default), REPEATABLE READ, SERIALIZABLE (strictest) and SNAPSHOT, which uses row versions so readers do not block writers. Read Committed Snapshot Isolation is often enabled to reduce blocking in busy OLTP apps.
37

Users report intermittent errors saying their transaction was chosen as a deadlock victim. How do you investigate and fix it?

Save to ▾
Show answer
A deadlock happens when two sessions each hold a lock the other needs. Get the deadlock graph from the system_health Extended Events session to see the statements and objects involved. Common fixes: access tables in the same order in all code paths, keep transactions short, add indexes so queries lock fewer rows, and consider RCSI. Also add retry logic in the app, since EF Core's SQL Server execution strategy can retry deadlocks.
38

A frequent query on Orders filtered by CustomerId shows expensive key lookups in its execution plan. How would you fix it?

Save to ▾
Show answer
A covering index contains every column a query needs, so SQL Server answers it from the index alone without key lookups to the clustered index. INCLUDE adds non-key columns to the leaf level only, keeping the index key small. For SELECT Name, Total FROM Orders WHERE CustomerId = 5, an index on CustomerId INCLUDE (Name, Total) covers it. Do not include too many columns, since every index slows writes.
39

A stored procedure is fast for most customers but very slow for one large customer, and sometimes slow for everyone after a restart. What could cause this?

Save to ▾
Show answer
This is parameter sniffing. SQL Server compiles a plan using the first parameter values it sees and reuses it. A plan built for a small customer, using index seeks, can be terrible for a huge one, and vice versa. Fixes include OPTION (RECOMPILE) for that statement, OPTIMIZE FOR, splitting logic for skewed values, or Query Store plan forcing. SQL Server 2022 adds Parameter Sensitive Plan optimisation to keep multiple plans.
40

An Orders table has 50 million rows and queries are slowing down, but most reports only need the last 12 months. What would you do?

Save to ▾
Show answer
First check indexes and query plans, since good indexing often solves it. Then archive older data: move rows older than a set period to an archive table or database in small batches during off-peak hours, keeping reports on history available separately. For ongoing growth, use table partitioning by month on OrderDate, which enables fast partition switching and lets queries scan only relevant partitions. Agree retention rules with the business first.
41

Your security team objects to storing the JWT in localStorage in your Angular app. What are the options?

Save to ▾
Show answer
localStorage is readable by any JavaScript on the page, so an XSS bug can steal the token. A safer pattern is to keep the short-lived access token in memory and store the refresh token in an HttpOnly, Secure, SameSite cookie that scripts cannot read. Even better is the backend-for-frontend pattern, where ASP.NET Core holds tokens server-side and the browser uses a session cookie. Add CSRF protection when using cookies.
42

A large Angular dashboard becomes sluggish because change detection runs constantly. How do OnPush and zoneless mode help?

Save to ▾
Show answer
Traditionally Zone.js patched browser events and timers, and after each one Angular checked every component for changes, top to bottom. OnPush makes a component re-check only when its inputs change by reference, an event occurs inside it, an async pipe emits or a signal it reads changes, which saves work in big screens. Zoneless mode removes Zone.js entirely and relies on signals and explicit triggers, reducing bundle size and improving performance.
43

Tell me about a time you led a team to deliver a complex feature.

Save to ▾
Show answer
As tech lead (Situation) I owned a vendor-payments module touching Angular, three APIs and SQL Server. My task was to deliver it in six weeks with four developers. I broke it into vertical slices, defined API contracts first, set up feature flags and reviewed every pull request within a day. When one developer struggled with EF Core, I paired with them. Result: we released on time with no critical bugs and two juniors grew into module owners.

Frequently asked questions

Who should practise hard .NET Full Stack questions?

Candidates targeting senior roles or top product companies, and anyone who finds the medium set easy.

How should I practise these?

Answer each question aloud before opening the answer, mark it as solved only when your answer matches the key idea, and save misses to Last-Minute Revision.

Other difficulty levels