OctogleHire
← Interview questions library

25 C# interview questions

Structure the C# interview loop so each stage answers a different risk question. Start with a 30-minute screen on recent .NET work, communication, and role fit. Follow with a practical coding exercise in C# 13/14 and .NET 9/10 that tests readable code, tests, async behavior, and debugging. Add a technical deep dive on ASP.NET Core, EF Core, dependency injection, observability, and production trade-offs. For senior roles, include system design focused on service boundaries, data consistency, security, and operations. Finish with a behavioral interview around ownership, incidents, code review, and cross-team work. Use the same rubric for every candidate and prefer “explain your reasoning” over trivia.

Junior C# questions

Fundamentals, learning speed and how they debug.

  1. 01You inherit an ASP.NET Core endpoint that sometimes hangs under load. How would you investigate before changing code?

    Listen for: A strong answer starts with reproducing the problem, checking logs, traces, thread pool metrics, request duration, dependency latency, and exceptions. They should mention async all the way, avoiding .Result or .Wait(), inspecting database calls, and using tools such as dotnet-counters, Application Insights, OpenTelemetry, or Visual Studio diagnostics.

    Red flag: They immediately suggest adding more servers or making every method async without measuring anything.

  2. 02How do you use nullable reference types in a C# project without making the code noisy or misleading?

    Listen for: Look for understanding that nullable annotations are a design tool, not runtime validation. Good answers mention enabling them gradually, fixing public contracts first, using guard clauses, annotating DTOs carefully, avoiding blanket null-forgiving operators, and pairing annotations with validation in ASP.NET Core model binding or FluentValidation.

    Red flag: They treat nullable warnings as compiler noise to disable or suppress everywhere.

  3. 03A teammate writes a long LINQ query that is hard to read and slower than expected. How would you review it?

    Listen for: They should separate readability from performance, ask whether it runs in memory or translates to SQL, and verify behavior with tests or generated SQL. Strong candidates discuss naming intermediate steps, avoiding repeated enumeration, knowing when loops are clearer, and checking allocations or database round trips before optimizing.

    Red flag: They claim LINQ is always slower than loops or always preferable because it is shorter.

  4. 04Explain the difference between transient, scoped, and singleton services in ASP.NET Core dependency injection using an example bug.

    Listen for: A good answer ties lifetimes to real behavior: scoped per web request, singleton for shared stateless services, transient for lightweight objects. They should identify bugs like a singleton capturing a DbContext or user-specific state, explain thread-safety concerns, and know how constructor injection reveals dependencies.

    Red flag: They memorize definitions but cannot explain why injecting a scoped service into a singleton is dangerous.

  5. 05An EF Core query works locally but times out in production. What would you check?

    Listen for: Listen for checking generated SQL, indexes, data volume, includes, projections, tracking, pagination, and N+1 queries. Good candidates mention using AsNoTracking for read paths, selecting only needed columns, query tags, execution plans, and environment differences such as connection strings, timeouts, and database statistics.

    Red flag: They assume EF Core is the problem and suggest replacing it with raw SQL immediately.

  6. 06How would you unit test a service that calls an external HTTP API and uses the current time?

    Listen for: They should isolate external dependencies using HttpClientFactory with a fake HttpMessageHandler, typed clients, or a test server. For time, they should mention TimeProvider in modern .NET or an injected clock abstraction. Good answers include testing success, failure, timeout, cancellation, and serialization behavior.

    Red flag: They suggest calling the real external API from unit tests and relying on the machine clock.

Mid-level C# questions

Independent delivery, trade-offs and code quality.

  1. 07Design a C# method that calls a downstream API with cancellation, timeout, and retry behavior. What trade-offs matter?

    Listen for: Strong answers distinguish caller cancellation from internal timeout, pass CancellationToken through all async calls, and avoid retrying non-idempotent operations blindly. They may use HttpClientFactory and Polly or Microsoft.Extensions.Resilience, handle transient status codes, add jitter, log attempts, and preserve useful error context without swallowing exceptions.

    Red flag: They add infinite retries or catch Exception and return null.

  2. 08How would you handle optimistic concurrency in an EF Core update flow?

    Listen for: Look for use of rowversion, concurrency tokens, or updated timestamps; handling DbUpdateConcurrencyException; reloading current values; and deciding whether to merge, reject, or ask the user to retry. Good candidates discuss transaction boundaries, user intent, audit trails, and tests that simulate two writers.

    Red flag: They rely on last write wins without recognizing the business impact.

  3. 09You need to add versioning to a public ASP.NET Core API. How would you approach it?

    Listen for: A solid answer considers compatibility before mechanics. They should discuss additive changes, deprecation, OpenAPI documents per version, contract tests, client communication, and whether URL, header, or media type versioning fits the organization. They should avoid leaking internal domain models directly as response contracts.

    Red flag: They change DTO shapes in place and expect clients to adapt.

  4. 10When would you use BackgroundService, Hangfire, Azure Functions, or a queue worker for background processing?

    Listen for: Good answers compare hosting, durability, retries, scale-out, scheduling, and operational visibility. They know BackgroundService is simple but tied to app lifetime, queues improve resilience, Hangfire helps with persisted jobs and dashboards, and serverless functions can suit event-driven workloads with clear cold-start and dependency trade-offs.

    Red flag: They choose one tool for all background work regardless of durability or failure handling.

  5. 11A production issue shows elevated latency but no obvious errors. How do you use logs, metrics, and traces to narrow it down?

    Listen for: They should describe correlation IDs, structured logs, RED or USE metrics, distributed traces across HTTP, database, and messaging calls, and comparing deploy timelines. Good answers mention OpenTelemetry, sampling, dashboards, percentiles rather than averages, and forming hypotheses before adding targeted instrumentation.

    Red flag: They say they would add more log lines everywhere and redeploy repeatedly.

  6. 12How do you find and reduce unnecessary allocations in a hot C# path without making the code unreadable?

    Listen for: Strong answers measure first with BenchmarkDotNet, dotnet-trace, PerfView, or Visual Studio profiler. They mention common sources such as string concatenation, LINQ in tight loops, boxing, closures, and large object heap pressure. They know Span<T>, ArrayPool<T>, and source generators can help but carry complexity.

    Red flag: They propose using unsafe code or Span<T> everywhere before profiling.

  7. 13How would you implement authorization for an ASP.NET Core endpoint that has both role-based and resource-specific rules?

    Listen for: Listen for separating authentication from authorization, using policies and handlers, checking ownership or tenant membership against the resource, and avoiding client-supplied claims as the only source of truth. Good answers mention tests for denied access, secure defaults, audit logging, and avoiding authorization only in the UI.

    Red flag: They only check whether the user has an Admin role and ignore resource boundaries.

Senior C# questions

Judgement, architecture and raising the team's bar.

  1. 14A growing .NET codebase has become hard to change. How do you decide between improving a modular monolith and splitting services?

    Listen for: Senior candidates should weigh team ownership, deployment friction, data boundaries, coupling, observability, and operational maturity. A strong answer favors clarifying domain modules, contracts, and tests before distribution. They should discuss incremental extraction, anti-corruption layers, and the cost of distributed transactions and debugging.

    Red flag: They equate microservices with good architecture and recommend splitting everything immediately.

  2. 15How would you plan a migration from .NET Framework or an older .NET Core service to .NET 10 LTS?

    Listen for: Look for inventorying dependencies, target frameworks, hosting model, configuration, authentication, EF version, build pipeline, and runtime behavior changes. Good answers use upgrade-assistant where helpful, migrate tests first, run side-by-side deployments, keep rollback paths, and address Windows-only APIs or legacy packages explicitly.

    Red flag: They treat the migration as a simple csproj edit and NuGet update.

  3. 16Describe how you would design resilience for a C# service that depends on several unreliable external systems.

    Listen for: Strong answers classify dependencies by criticality and failure mode, then apply timeouts, bulkheads, circuit breakers, retries with jitter, fallbacks, and idempotency. They should mention Microsoft.Extensions.Resilience or Polly, health checks that do not amplify outages, backpressure, and clear user-facing degradation behavior.

    Red flag: They wrap every call in retries and call the system resilient.

  4. 17How do you handle data consistency across services when one business action updates multiple systems?

    Listen for: Listen for explicit trade-offs between strong consistency and eventual consistency. Good answers mention transactional outbox, inbox/idempotency, sagas or process managers, message ordering limits, compensating actions, and reconciliation jobs. They should tie the choice to business invariants rather than forcing distributed transactions.

    Red flag: They assume a single database transaction can safely cover all services and message brokers.

  5. 18What engineering practices would you introduce to keep a C# codebase healthy as the team grows?

    Listen for: A senior answer includes clear ownership, coding standards enforced by analyzers, nullable reference types, CI quality gates, meaningful tests, dependency update policy, architecture decision records, and review norms. They should avoid process for its own sake and explain how practices reduce real defects or delivery risk.

    Red flag: They focus only on personal code style preferences and mandatory approvals.

  6. 19How would you design deployment and observability for an ASP.NET Core service running in containers?

    Listen for: Look for container health probes, graceful shutdown, configuration by environment, secret management, structured logging, OpenTelemetry traces and metrics, dashboards, alerts tied to user impact, and rollback strategy. Good answers mention readiness versus liveness, resource limits, startup time, and validating migrations during deployment.

    Red flag: They consider deployment done once the Dockerfile builds.

  7. 20Tell me about a production incident you led or would lead. What does good technical leadership look like during and after it?

    Listen for: Strong candidates describe stabilizing the system, assigning roles, communicating clearly, preserving evidence, and making reversible changes. Afterward, they run blameless review, identify contributing factors, prioritize fixes, improve alerts or runbooks, and follow through. They distinguish urgency during mitigation from rigor during root-cause analysis.

    Red flag: They focus on finding who broke it rather than how the system allowed it.

System design C# questions

Designing real systems end to end.

  1. 21Design a multi-tenant ASP.NET Core SaaS API where each tenant needs data isolation, custom authorization, and usage limits.

    Listen for: A strong design covers tenant resolution, authentication, per-tenant authorization, database isolation options, EF Core global query filters with safeguards, rate limiting middleware, auditing, and observability by tenant. They should discuss noisy-neighbor risks, background jobs, migrations, and how tests prevent cross-tenant data leaks.

    Red flag: They rely on a tenantId sent by the client and trust every query to remember the filter.

  2. 22Design a C# event processing service that consumes messages from a broker and updates a SQL database exactly once from the business perspective.

    Listen for: Listen for at-least-once delivery assumptions, idempotency keys, inbox tables, transactional updates, poison message handling, retries with backoff, dead-letter queues, and metrics. Good answers explain why true exactly-once is usually the wrong framing and how to make duplicate processing harmless.

    Red flag: They assume the broker guarantees exactly-once behavior and skip idempotency.

  3. 23Design an import pipeline for large customer CSV files in .NET, including validation, progress, and partial failures.

    Listen for: Good answers stream files rather than loading them fully, validate records in batches, persist import state, report progress, and separate syntax errors from business rule failures. They discuss background processing, cancellation, retries, database batching, user-visible error reports, and memory profiling for large inputs.

    Red flag: They read the entire file into a List and process it inside one web request.

  4. 24Design authentication and authorization for a B2B ASP.NET Core API used by browser clients and machine-to-machine integrations.

    Listen for: A strong answer distinguishes user flows from client credentials, validates JWT issuer, audience, lifetime, and signing keys, and maps claims to internal permissions. They discuss policy-based authorization, tenant context, token rotation, secret storage, scopes, audit logs, and avoiding business authorization solely in the identity provider.

    Red flag: They decode the JWT and trust whatever claims are present without validation or internal checks.

  5. 25Design a low-latency product catalog API in C# backed by SQL Server, with frequent reads and occasional writes.

    Listen for: Look for clear read models, projection queries, caching strategy, invalidation, ETags, pagination, and database indexing. Good answers compare IMemoryCache, Redis, output caching, and CDN behavior where applicable. They also address stale data tolerance, cache stampede prevention, observability, and fallback behavior when cache is unavailable.

    Red flag: They add caching everywhere without defining freshness rules or invalidation.

Practical task · 2–3 hours

Build and test a small order status API

Create a .NET 10 ASP.NET Core service with two endpoints: submit an order status update and retrieve the latest status history for an order. Store data in SQLite or SQL Server LocalDB using EF Core. Validate input, handle duplicate update IDs idempotently, and return appropriate problem details for errors. Include cancellation token flow, structured logging, and unit or integration tests for success, validation failure, duplicate submission, and not-found behavior. Keep the solution small enough to review in one sitting, and include a short README explaining assumptions and trade-offs.

How to evaluate it

  • Clear API contracts, validation, and HTTP status choices
  • Correct async usage, cancellation flow, and idempotency handling
  • Readable C# with appropriate dependency injection and separation of concerns
  • EF Core usage, migrations or schema setup, and efficient queries
  • Test quality, README clarity, and evidence of pragmatic trade-offs

Rather skip the interview loop?

Every Octogle C# engineer has already passed a technical assessment, system design and a live interview with an engineer who has shipped C#. Send a brief and get 3–5 scored profiles in 48 hours.