Information Technology
.NET Interview Questions & Answers
The .NET platform and base class library.
.NET CLI, SDK & Project Structure (csproj)
All 15 questionsThe .NET SDK includes everything needed to build, run, and publish .NET applications: the compiler (Roslyn for C#), the dotnet CLI, MSBuild, and the runtime. The .NET Runtime alone…
The dotnet CLI is the cross-platform command-line interface for creating, building, running, testing, and publishing .NET projects. Common commands include `dotnet new` (scaffold a…
- What is the structure and purpose of a .csproj file in a modern SDK-style .NET project? Intermediate
A .csproj file is an MSBuild XML project file describing how to build a project: target framework, package references, project references, compiler settings, and output type. Moder…
A .sln file is a text-based manifest listing one or more related projects (each with its own .csproj) that are built and managed together, along with build configurations (Debug/Re…
dotnet build compiles the project into assemblies in the output directory (bin/Debug or bin/Release), suitable for local development but not necessarily deployment-ready. dotnet pu…
.NET vs .NET Framework
All 16 questions.NET Framework is the original, Windows-only implementation of .NET dating back to 2002, tightly coupled to Windows and installed as a shared system component. .NET (unified since…
- Why did Microsoft skip version 4 and name the unified platform '.NET 5' instead of '.NET Core 4'? Intermediate
Microsoft skipped .NET 4 specifically to avoid confusion with .NET Framework 4.x, since the new unified platform was meant to signal a clean break as the singular future of .NET --…
.NET Standard was a formal specification of APIs that both .NET Framework and .NET Core (and Xamarin, Mono, etc.) committed to implementing, letting library authors target one .NET…
- What major APIs or features exist in .NET Framework but are unavailable or different in modern .NET? Advanced
Notable gaps include: WCF server-side hosting (client-side exists via a community package, CoreWCF is a separate reimplementation), ASP.NET Web Forms (no equivalent, replaced conce…
- How does performance typically compare between .NET Framework and modern .NET (e.g., .NET 8)? Intermediate
Modern .NET has received years of dedicated, continuous performance investment (documented in Microsoft's annual 'Performance Improvements in .NET' posts) covering JIT compilation,…
API Versioning
All 15 questionsAPI versioning lets you evolve an API's contract (adding fields, changing behavior, removing deprecated endpoints) without breaking existing clients that depend on the current beha…
- What are the main strategies for versioning an ASP.NET Core API (URL, query string, header, media type)? Intermediate
URL segment versioning (/api/v1/products) is the most visible and cache-friendly approach. Query string versioning (/api/products?api-version=1.0) keeps URLs stable but is less dis…
- How do you implement URL-based API versioning using the Asp.Versioning.Mvc package in ASP.NET Core? Intermediate
The Asp.Versioning packages (successor to Microsoft.AspNetCore.Mvc.Versioning) let you register API versioning services, define supported versions per controller/action via [ApiVer…
Instead of separate controller classes per version, you can apply multiple [ApiVersion] attributes to one controller and use [MapToApiVersion("x.0")] on individual actions to indic…
The Asp.Versioning library can automatically add an `api-supported-versions` header (listing currently supported versions) and an `api-deprecated-versions` header (listing versions…
ASP.NET Core Middleware & Request Pipeline
All 17 questionsMiddleware are components assembled into a pipeline that handles every incoming HTTP request and outgoing response. Each middleware can perform work before and after calling the ne…
Middleware executes in exactly the order it's registered for the 'incoming' phase, then unwinds in reverse order for the 'outgoing' phase -- so registering exception handling befor…
- How do you write a custom middleware component as a reusable class instead of an inline lambda? Intermediate
A class-based middleware implements a constructor accepting RequestDelegate next (and typically other injected services), and an InvokeAsync (or Invoke) method containing the actua…
Since class-based middleware is instantiated once as a singleton for the app's lifetime, you can't inject scoped services (like a DbContext) directly into the constructor -- instea…
- What's the difference between app.Use, app.Run, and app.Map in configuring the middleware pipeline? Intermediate
app.Use adds middleware that can call next() to continue the pipeline (non-terminal). app.Run adds terminal middleware that never calls next() -- it always ends the pipeline at tha…
Assemblies & NuGet
All 15 questionsAn assembly is the fundamental unit of deployment and versioning in .NET -- a compiled .dll or .exe file containing IL (Intermediate Language) code, type metadata, and a manifest d…
NuGet is .NET's official package manager, providing a standardized way to discover, install, update, and share reusable libraries (packages) across projects, avoiding the need to m…
The GAC was a machine-wide repository in .NET Framework for storing strongly-named shared assemblies, letting multiple applications reference one common copy instead of each having…
Modern NuGet uses a resolution algorithm that generally selects the lowest version that satisfies all direct and transitive constraints for older-style ranges, but with PackageRefe…
Central Package Management lets you specify all package versions once in a repository-root Directory.Packages.props file, with individual project .csproj files referencing packages…
Authentication & Authorization (Identity, JWT, OAuth)
All 16 questionsAuthentication answers 'who are you?' -- verifying a user's identity, typically producing a ClaimsPrincipal representing the authenticated user. Authorization answers 'what are you…
A client authenticates once (e.g., with credentials) and receives a signed JWT containing claims about the user (identity, roles, expiration) encoded in its payload. For subsequent…
Claims are key-value pairs embedded in a JWT's payload describing attributes about the authenticated subject (standard ones include sub, exp, iss, aud; custom ones might include ro…
ASP.NET Core Identity is a membership system providing user registration, password hashing and validation, email confirmation, two-factor authentication, external login providers (…
The Authorization Code flow has the client redirect the user to an authorization server to authenticate and consent, receive a short-lived authorization code via redirect, then exc…
Background Services
All 15 questionsBackgroundService is an abstract base class implementing IHostedService, designed for long-running background work that runs alongside the main application (like an ASP.NET Core we…
- How does graceful shutdown work for a BackgroundService, and what role does CancellationToken play? Intermediate
When the host begins shutting down (e.g., SIGTERM in a container, or Ctrl+C locally), it signals the CancellationToken passed to ExecuteAsync, and gives the service a configurable…
Since BackgroundService instances are singletons for the app's lifetime, you cannot inject scoped services directly into the constructor -- instead, inject IServiceScopeFactory (or…
An unhandled exception escaping ExecuteAsync causes the BackgroundService to stop entirely (and by default, in .NET 6+, can even trigger the whole host to shut down if configured),…
Introduced in .NET 8, IHostedLifecycleService adds StartingAsync, StartedAsync, StoppingAsync, and StoppedAsync hooks around the existing StartAsync/StopAsync, letting you run logi…
Blazor (Server & WebAssembly)
All 15 questionsBlazor is a framework for building interactive web UIs using C# and .NET instead of JavaScript. Blazor Server runs application logic on the server, with the browser maintaining a p…
- How does Blazor Server's reliance on a persistent SignalR connection affect its behavior under network interruptions? Intermediate
Since all UI state and event handling logic actually executes on the server, a Blazor Server app's interactivity entirely depends on its SignalR connection -- if the connection dro…
- What is a 'circuit' in Blazor Server, and how does server-side state management work across it? Advanced
A circuit represents the server-side connection and state for one Blazor Server user session -- it holds the component tree, its current render state, and any DHTML event handlers,…
- How do Razor components (.razor files) combine markup and C# code, and what is the @code block? Intermediate
A .razor component file mixes HTML-like markup with embedded C# expressions (using @ syntax) for data binding and control flow, plus an @code block containing the component's C# cl…
@bind creates a two-way binding between a component field/property and an HTML element's value, automatically wiring up both the value attribute and an appropriate change event (on…
Caching (In-Memory, Distributed & Redis)
All 15 questionsIMemoryCache is a built-in in-process cache storing key-value pairs directly in the application's own memory, ideal for single-instance applications or data that's acceptable to re…
- What is the difference between absolute expiration and sliding expiration when configuring a cache entry? Intermediate
Absolute expiration removes an entry at a fixed point in time regardless of how recently it was accessed, guaranteeing data won't become stale beyond a hard limit. Sliding expirati…
- What is IDistributedCache, and how does it differ from IMemoryCache in a multi-instance deployment? Advanced
IDistributedCache is an abstraction over an external, shared cache store (like Redis or SQL Server) that all instances of a horizontally-scaled application read from and write to c…
- How do you configure and use Redis as a distributed cache in ASP.NET Core with StackExchange.Redis? Intermediate
Install the Microsoft.Extensions.Caching.StackExchangeRedis package, register it via AddStackExchangeRedisCache with a connection string, then inject IDistributedCache to get/set v…
A cache stampede occurs when a popular cache entry expires and many concurrent requests simultaneously discover the cache miss, all racing to recompute and repopulate the same expe…
CI/CD, Publishing & Deployment
All 16 questionsA typical pipeline includes: restore dependencies (dotnet restore), build (dotnet build), run automated tests (dotnet test), publish deployable artifacts (dotnet publish), and depl…
- How do you configure a GitHub Actions workflow to build, test, and publish a .NET application? Intermediate
A GitHub Actions workflow YAML file defines jobs with steps using the actions/setup-dotnet action to install the required SDK version, followed by standard dotnet CLI commands, wit…
Blue-green deployment maintains two identical production environments (blue = current, green = new), routing all traffic to green only after it's fully deployed and verified, enabl…
CI/CD platforms provide encrypted secret storage (GitHub Actions Secrets, Azure DevOps variable groups with secret variables, GitLab CI/CD variables) injected as environment variab…
- How do you set up automated database migrations as part of a .NET CI/CD deployment pipeline safely? Advanced
Common safe approaches include: running EF Core migrations (`dotnet ef database update`) as a separate pipeline step before deploying application code (so the schema is ready befor…
CLR & Runtime
All 19 questionsThe CLR is the execution engine of .NET, responsible for managing memory (allocation and garbage collection), just-in-time (JIT) compiling IL code to native machine code, enforcing…
- What is JIT (Just-In-Time) compilation, and how does it differ from ahead-of-time (AOT) compilation? Intermediate
JIT compilation translates IL into native machine code at runtime, immediately before a method is first executed, allowing the CLR to optimize compiled code based on the actual run…
- What is tiered compilation, and how does it balance fast startup with peak execution performance? Advanced
Tiered compilation JIT-compiles a method quickly with minimal optimization on its first call (Tier 0, fast to produce but slower to execute), then, if the method is called frequent…
Value types (structs, primitives like int/bool/double) are typically allocated on the stack (or inline within a containing object/array) and copied by value when assigned or passed…
Boxing wraps a value type in a heap-allocated object so it can be treated as a reference type (e.g., assigning an int to an object variable or adding it to a non-generic collection…
Configuration & Options
All 15 questionsIConfiguration builds a unified key-value configuration tree by combining multiple providers in a specific registration order, where later-registered providers override earlier one…
- What is the Options pattern, and why is it preferred over directly injecting IConfiguration into services? Intermediate
The Options pattern binds a strongly-typed C# class to a section of configuration (via IOptions , IOptionsSnapshot , or IOptionsMonitor ), giving you compile-time type safety, Inte…
IOptions is registered as a singleton, computed once at first access and never refreshed even if the underlying configuration source changes at runtime -- suitable for genuinely st…
- How does appsettings.{Environment}.json layering work, and how is the current environment determined? Intermediate
ASP.NET Core loads appsettings.json first as a base configuration, then layers appsettings.{EnvironmentName}.json on top (where settings in the environment-specific file override m…
The configuration binder uses reflection to match configuration keys (flattened into a colon-delimited hierarchy internally, e.g., "Parent:Child:Grandchild") to corresponding prope…
CORS & Cross-Origin Resource Sharing
All 15 questionsCORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different origin (different scheme, domain, or port) than th…
- How do you configure a CORS policy in ASP.NET Core to allow requests from specific origins? Intermediate
Register a named CORS policy via AddCors specifying allowed origins, methods, and headers, then apply it either globally with UseCors(policyName) in the middleware pipeline or per-…
For 'non-simple' requests (using methods other than GET/HEAD/POST, custom headers, or a Content-Type other than a few basic ones), the browser automatically sends an OPTIONS prefli…
- What does AllowCredentials() do in a CORS policy, and why can't it be combined with a wildcard origin? Intermediate
AllowCredentials() permits cross-origin requests to include credentials (cookies, HTTP authentication, client certificates), required for cookie-based authentication to work across…
Register multiple named policies with AddCors, then apply a specific one to individual controllers or actions using [EnableCors("PolicyName")], overriding whatever the default/glob…
Dependency Injection
All 16 questions- What is dependency injection, and how does ASP.NET Core's built-in DI container support it? Beginner
Dependency injection is a design pattern where a class receives its dependencies (other objects it needs to function) from an external source rather than creating them itself, prom…
- What is the difference between Singleton, Scoped, and Transient service lifetimes in ASP.NET Core's DI container? Intermediate
Singleton creates one instance for the entire application lifetime, shared across all requests and threads. Scoped creates one instance per client request (or per explicitly create…
A captive dependency occurs when a longer-lived service (Singleton) depends on a shorter-lived service (Scoped or Transient), effectively 'capturing' that shorter-lived instance fo…
- How do you register multiple implementations of the same interface, and how do you resolve all of them together? Intermediate
Calling AddScoped/AddSingleton/AddTransient multiple times for the same interface with different implementations registers all of them; injecting IEnumerable resolves the full coll…
Keyed services let you register multiple implementations of the same interface under distinct string or object keys, then resolve a specific one explicitly using [FromKeyedServices…
Diagnostics & Performance
All 16 questions- What tools does .NET provide for basic application diagnostics, and what is dotnet-trace used for? Beginner
The .NET SDK includes global diagnostic tools installable via `dotnet tool install -g`: dotnet-trace collects CPU and runtime event traces for performance analysis, dotnet-counters…
- How does dotnet-counters provide live performance monitoring, and what key metrics does it expose by default? Intermediate
dotnet-counters connects to a running .NET process and streams live performance counters to the console (or exports them), including built-in metrics like CPU usage, GC heap size a…
dotnet-gcdump collects a snapshot of the entire managed heap from a running process (triggering a full GC first to ensure only genuinely reachable objects are captured), producing…
- What is Application Insights (or OpenTelemetry) integration, and what value does it add over basic logging? Intermediate
Application Insights (and the vendor-neutral OpenTelemetry standard it increasingly supports) provides distributed tracing (following a single logical request across multiple servi…
EventCounter (older API) and Meter/Instrument (newer, OpenTelemetry-aligned API introduced in .NET 6) let application code publish custom numeric metrics (counters, gauges, histogr…
Docker & Containerization
All 16 questionsThe sdk image (mcr.microsoft.com/dotnet/sdk) includes the full SDK for building and publishing applications -- large, used only in build stages. The aspnet image (mcr.microsoft.com…
A multi-stage Dockerfile uses a build stage (based on the full SDK image) to restore, compile, and publish the application, then a separate, final stage (based on a minimal runtime…
Docker caches each instruction's layer based on its inputs; by copying only the .csproj (which changes infrequently) and running dotnet restore before copying the rest of the sourc…
Modern .NET automatically detects container memory and CPU limits (via cgroup information on Linux) and configures the garbage collector and thread pool accordingly by default -- t…
For containers, Native AOT produces a fully self-contained native executable with no separate .NET runtime dependency, letting you use an extremely minimal base image (even distrol…
Entity Framework Core & Data Access
All 16 questions- What is Entity Framework Core, and how does it relate to the Repository and Unit of Work patterns? Beginner
EF Core is an object-relational mapper (ORM) that lets you work with a relational database using C# objects (entities) and LINQ queries instead of writing raw SQL by hand, translat…
- What is the difference between EF Core's Code-First (migrations) approach and Database-First (scaffolding) approach? Intermediate
Code-First defines your data model as C# classes first, then uses migrations to generate and apply corresponding database schema changes -- ideal for new projects where the applica…
By default, EF Core's DbContext tracks every entity returned by a query, recording a snapshot of its original values so SaveChanges can detect and generate SQL for exactly what cha…
- What is the N+1 query problem in EF Core, and how does eager loading with Include() solve it? Intermediate
The N+1 problem occurs when code queries a list of N entities, then separately queries related data for each one individually inside a loop, resulting in 1 initial query plus N add…
`dotnet ef migrations add ` compares your current model against the last migration's snapshot and generates a new migration class (with Up/Down methods describing the schema change…
Generic Host
All 15 questionsThe Generic Host (IHost, built via Host.CreateApplicationBuilder or WebApplication.CreateBuilder) provides a unified application startup model handling dependency injection contain…
- What is the difference between Host.CreateApplicationBuilder and the older Host.CreateDefaultBuilder? Intermediate
Host.CreateApplicationBuilder (introduced in .NET 7) is the modern, minimal-hosting-model-aligned builder returning a HostApplicationBuilder with more direct, immediate access to S…
The host registers signal handlers (via IHostApplicationLifetime and platform-specific mechanisms) for graceful shutdown signals -- SIGTERM/SIGINT on Linux/macOS, Ctrl+C or service…
- How does the Generic Host integrate configuration, logging, and dependency injection into a single unified builder? Intermediate
HostApplicationBuilder (and its WebApplicationBuilder subclass) exposes .Configuration (an IConfigurationBuilder pre-populated with the standard providers), .Services (an IServiceC…
You can register both regular services and one or more IHostedService/BackgroundService implementations on the same host, with hosted services starting automatically on host.Run()…
Global Exception Handling & Middleware
All 15 questions- What is the purpose of global exception handling middleware in an ASP.NET Core application? Beginner
Global exception handling middleware catches unhandled exceptions thrown anywhere downstream in the pipeline (controllers, other middleware, business logic), preventing them from c…
IExceptionHandler defines a TryHandleAsync(HttpContext, Exception, CancellationToken) method that you implement as a proper, testable, DI-injectable class rather than an inline del…
ProblemDetails is a standardized JSON format for HTTP API error responses, including fields like type, title, status, detail, and instance, providing a consistent, machine-and-huma…
- How do you map different exception types to different HTTP status codes in a global exception handler? Intermediate
Inside your exception handler (whether the older UseExceptionHandler lambda or the newer IExceptionHandler), inspect the caught exception's type (or a custom base exception hierarc…
Production error responses should never include raw exception messages, stack traces, internal file paths, database connection details, or any information revealing internal archit…
gRPC Services
All 15 questionsgRPC is a high-performance RPC (Remote Procedure Call) framework built on HTTP/2, using Protocol Buffers (protobuf) as its binary serialization format for both requests and respons…
A .proto file declares message types (structured data with numbered fields) and service definitions (RPC method signatures) using protobuf's interface definition language; the Grpc…
Unary (single request, single response) is the most common, equivalent to a typical REST call. Server streaming (single request, stream of responses) suits scenarios like subscribi…
- How do you implement a gRPC server method in ASP.NET Core, and how does it integrate with the standard hosting model? Intermediate
A gRPC service class extends the code-generated base class (from the .proto file) and overrides its virtual RPC methods, registered via MapGrpcService () in the endpoint routing co…
gRPC uses its own set of standardized status codes (like NotFound, InvalidArgument, PermissionDenied, Internal, Unavailable) distinct from HTTP status codes, communicated via gRPC…