Skip to content

Scenario-Based .NET Full Stack Interview Questions

48 questions with answers. Real-work situations — broken dashboards, flaky tests, unclear requirements — and how a strong .net developer would handle them.

How to approach these questions

Clarify the situation, list likely causes, say how you would check each one, then give the fix and how you would stop it happening again.

Solved — scenario-basedStart 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

You are designing a type to hold a 2D point used millions of times in a calculation. Struct or class?

Save to ▾
Show answer
A struct is a good fit because the point is small, logically a single value and created in huge numbers. Structs avoid heap allocation and GC pressure when stored in arrays or locals. Make it a readonly struct so it is immutable and avoids defensive copies. Choose a class instead if the type is large, needs inheritance, or is frequently boxed through interfaces, since copying and boxing remove the benefit.
02

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.
03

A report builder concatenates 50,000 rows into one string with += and takes several seconds. What do you change?

Save to ▾
Show answer
Each += creates a new string and copies everything built so far, so the cost grows quadratically. Replace it with a StringBuilder, ideally created with an estimated capacity, and call Append or AppendLine in the loop, then ToString once at the end. For very large output, write directly to a StreamWriter or the response stream instead of building the whole string in memory.
04

You need to add a new method to a widely implemented interface without breaking existing classes. How can you do it?

OOP in C#Medium
Save to ▾
Show answer
Since C# 8, an interface can provide a method body. Classes implementing the interface get that behaviour without writing it, though they can override it. The main use is evolving a published interface: you can add a new member without breaking every existing implementation. The default method is only callable through the interface type, not the class, and overusing it blurs the line with abstract classes.
05

A teammate created a deep inheritance chain Employee > Manager > SeniorManager > RegionalHead to add features. What would you suggest?

OOP in C#Medium
Save to ▾
Show answer
Deep hierarchies are fragile: a change in a base class ripples into every child, and behaviours that do not fit the tree get duplicated. I would suggest composition over inheritance. Keep a single Employee entity and give it composed parts such as a Role, an ApprovalPolicy and a list of Permissions, injected as interfaces. New behaviour then means a new policy class, not a new subclass, which is easier to test.
06

Which design patterns do you commonly see in ASP.NET Core projects?

OOP in C#Medium
Save to ▾
Show answer
Dependency Injection is built in. The Repository and Unit of Work patterns wrap data access, although DbContext already implements them. Factory creates objects by type, for example IHttpClientFactory. Strategy swaps algorithms, such as different tax or discount rules, behind one interface. Options pattern binds configuration to classes. Middleware is a Chain of Responsibility, and Mediator libraries implement CQRS by sending commands to handlers.
07

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.
08

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.
09

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>.
10

Your code builds a LINQ query over a database, then calls Count() and later loops over it, and the logs show two SQL queries. Why, and how do you fix it?

Save to ▾
Show answer
This is multiple enumeration caused by deferred execution. The variable holds a query, not data, so Count runs one SQL statement and the foreach runs another. Besides extra load, the two results may differ if data changes in between. Materialise once with var list = await query.ToListAsync(), then use list.Count and loop over the list. Code analysers flag possible multiple enumeration of IEnumerable as a warning.
11

A job matches 2 lakh uploaded records against 2 lakh existing IDs using list.Where(x => existingIds.Contains(x.Id)) and takes minutes. What is wrong?

Save to ▾
Show answer
existingIds is a List, so Contains is O(n) and the whole operation becomes O(n x m), around 40 billion comparisons. Convert the IDs to a HashSet<int> first, making each lookup O(1) and the job run in milliseconds. If you also need associated data, build a Dictionary keyed by ID. Always check data structure complexity before parallelising or adding hardware.
12

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.
13

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.
14

You need to remove inactive users from a List<User> while looping through it with foreach, and you get an InvalidOperationException. How do you fix it?

Save to ▾
Show answer
foreach does not allow modifying the collection it is enumerating, so the enumerator throws. The simplest fix is users.RemoveAll(u => !u.IsActive), which is efficient and clear. Alternatives are looping backwards with a for loop and RemoveAt, or building a new filtered list with Where and ToList. For a dictionary, collect keys to remove first, then remove them after the loop.
15

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.
16

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.
17

You must resize 10,000 images and also call an external API for 10,000 records. Which approach do you use for each task?

Save to ▾
Show answer
Parallel.ForEach is for CPU-bound work, such as resizing thousands of images, where splitting work across cores speeds things up. async/await is for I/O-bound work, where you mostly wait on networks or disks. Using Parallel.ForEach for HTTP calls wastes threads while they wait. For many concurrent I/O operations with a limit, use Parallel.ForEachAsync with MaxDegreeOfParallelism, available since .NET 6.
18

A dashboard API calls three independent services one after another, each taking about 1 second. How can you make it faster?

Save to ▾
Show answer
Because the calls do not depend on each other, start all three tasks first without awaiting, then await Task.WhenAll. Total time becomes roughly the slowest call, about 1 second instead of 3. Add a timeout and handle failure of one service gracefully, for example showing partial data. If the same data is requested often, also add caching so most requests skip the calls entirely.
19

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.
20

A developer wraps every database call in Task.Run inside ASP.NET Core controllers to make them async. Is this a good idea?

Save to ▾
Show answer
No. Task.Run moves work to another thread pool thread, but the request still waits for it, so you use two threads instead of one and gain nothing. The database call itself is still blocking. The correct approach is to use true async APIs like ToListAsync and SaveChangesAsync, which release the thread during I/O. Task.Run makes sense mainly in desktop apps to keep the UI thread free.
21

Users trigger a large Excel report that takes 3 minutes, and the HTTP request times out. How would you redesign it?

Save to ▾
Show answer
Make it asynchronous at the workflow level. The API validates the request, saves a job record and returns 202 Accepted with a job ID. A background worker, using a queue such as a Channel, Hangfire or a message broker, generates the file and stores it in blob storage. The UI polls a status endpoint or receives a SignalR notification, then downloads the file. This avoids timeouts and survives retries.
22

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.
23

An API creates a new HttpClient inside a using block for every outgoing call, and under load you see socket exhaustion errors. How do you fix it?

Save to ▾
Show answer
Disposing HttpClient does not immediately free the underlying socket; connections stay in TIME_WAIT, so thousands of short-lived clients exhaust ports. A single static client fixes that but misses DNS changes. The recommended fix is IHttpClientFactory: register builder.Services.AddHttpClient<PaymentClient>() and inject the typed client. The factory pools and rotates handlers, and you can add resilience with Microsoft.Extensions.Http.Resilience for retries and timeouts.
24

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.
25

You must change an API response format, but an older mobile app version still calls it. How do you avoid breaking those users?

Save to ▾
Show answer
Versioning lets you change contracts without breaking existing clients such as mobile apps that users have not updated. Common approaches are URL segments (/api/v1/orders), query strings (?api-version=2.0) and headers. The Asp.Versioning library supports all of them and integrates with OpenAPI docs. URL versioning is the most visible and cache-friendly. Keep old versions running for a published period, then deprecate them with headers.
26

Where should you store secrets like connection strings and API keys in an ASP.NET Core app?

Save to ▾
Show answer
Never commit them in appsettings.json. During development use the Secret Manager (dotnet user-secrets), which stores them outside the project folder. In production use environment variables or, better, a vault such as Azure Key Vault or AWS Secrets Manager, loaded through a configuration provider and accessed with managed identity so no credential sits in code. Rotate secrets regularly and restrict who can read them.
27

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.
28

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.
29

A page listing 100 orders with customer names runs 101 SQL queries. What is the problem and how do you fix it?

Save to ▾
Show answer
This is the N+1 problem: one query loads the orders, then lazy loading fires a separate query for each order's Customer. Fix it by loading everything in one query, either with Include(o => o.Customer) or better with a projection: Select(o => new OrderListDto(o.Id, o.Total, o.Customer.Name)), which fetches only needed columns via a join. Turn on EF Core logging to spot such patterns early.
30

A read-only product listing endpoint in EF Core uses a lot of memory and CPU. What simple change helps, and why?

Save to ▾
Show answer
By default, EF Core tracks every entity it loads so it can detect changes on SaveChanges, which costs memory and CPU. AsNoTracking tells EF Core not to track the results, making read-only queries faster and lighter. Use it for lists, reports and GET endpoints where you will not update the data. AsNoTrackingWithIdentityResolution avoids duplicate instances of the same entity in results while still skipping tracking.
31

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.
32

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.
33

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.
34

A developer runs two EF Core queries in parallel with Task.WhenAll on the same DbContext and gets an InvalidOperationException. Why?

Save to ▾
Show answer
DbContext is not thread-safe and supports only one active operation at a time, so starting a second query before the first finishes throws 'A second operation was started on this context instance'. Either await the queries one after another, or create a separate context for each parallel query using IDbContextFactory. Usually sequential queries are fine; parallelism only helps when the queries are slow and independent.
35

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.
36

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.
37

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.
38

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.
39

A query that used to run in 1 second now takes 30 seconds. How do you troubleshoot it?

Save to ▾
Show answer
Capture the actual execution plan and look for table or index scans on large tables, key lookups, big differences between estimated and actual rows, and warnings like implicit conversions or spills to tempdb. Check missing or fragmented indexes and outdated statistics, and update them. Use Query Store to compare the old and new plans; if a plan regressed, you can force the good plan while fixing the root cause.
40

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.
41

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.
42

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.
43

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.
44

Your Angular app on localhost:4200 gets a CORS error when calling the ASP.NET Core API on localhost:5001. How do you fix it?

Save to ▾
Show answer
The browser blocks the call because the origins differ and the API sends no CORS headers. In the API, register a policy with AddCors allowing http://localhost:4200, the needed methods and headers, and call app.UseCors before UseAuthorization. Alternatively, use the Angular dev server proxy (proxy.conf.json) to forward /api calls, so the browser sees the same origin. In production, configure the real front-end domain, not AllowAnyOrigin.
45

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.
46

Your Angular app's first load is slow on mobile because the main bundle is very large. How does lazy loading of routes help?

Save to ▾
Show answer
Lazy loading splits the app into chunks that download only when the user navigates to that route, so the initial bundle is smaller and the first page loads faster, especially on mobile data. In Angular use loadComponent or loadChildren with a dynamic import in the route config; in React use React.lazy with Suspense or the router's lazy option. Angular's @defer blocks can also delay heavy parts of a page.
47

An admin page renders 20,000 rows in a table and the browser freezes. How do you fix it?

Save to ▾
Show answer
Do not send or render everything at once. Add server-side paging, sorting and filtering in the ASP.NET Core API so the page loads perhaps 50 rows at a time. If users truly need to scroll a long list, use virtual scrolling, such as Angular CDK virtual scroll or TanStack Virtual in React, so only visible rows exist in the DOM. Also use trackBy or keys, and debounce search inputs.
48

How would you deploy an Angular or React front end together with an ASP.NET Core API?

Save to ▾
Show answer
Two common options exist. Build the SPA with ng build or npm run build and serve the static files from the API's wwwroot with UseStaticFiles and MapFallbackToFile, giving one deployment and no CORS. Or host the SPA separately on a CDN or static hosting such as Azure Static Web Apps and the API on App Service or containers, which scales independently. Use environment config for API URLs and a CI/CD pipeline for both.

Frequently asked questions

Why are scenario-based questions important?

They show how you think on real problems. Interviewers use them to separate people who memorised definitions from people who have done the work.

How should I answer them?

Clarify the situation, list likely causes, say how you would check each one, then give the fix and how you would stop it happening again.