Advertisement

Information Technology

.NET Interview Questions & Answers

The .NET platform and base class library.

20topics 313questions last updated
Advertisement

.NET CLI, SDK & Project Structure (csproj)

All 15 questions
  1. The .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…

  2. 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…

  3. 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…

  4. 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…

  5. 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
  1. .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…

  2. 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 --…

  3. .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…

  4. 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…

  5. 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 questions
  1. API 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…

  2. 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…

  3. The Asp.Versioning packages (successor to Microsoft.AspNetCore.Mvc.Versioning) let you register API versioning services, define supported versions per controller/action via [ApiVer…

  4. 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…

  5. 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 questions
  1. Middleware 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…

  2. 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…

  3. A class-based middleware implements a constructor accepting RequestDelegate next (and typically other injected services), and an InvokeAsync (or Invoke) method containing the actua…

  4. 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…

  5. 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 questions
  1. An 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. Authentication answers 'who are you?' -- verifying a user's identity, typically producing a ClaimsPrincipal representing the authenticated user. Authorization answers 'what are you…

  2. 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…

  3. 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…

  4. ASP.NET Core Identity is a membership system providing user registration, password hashing and validation, email confirmation, two-factor authentication, external login providers (…

  5. 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 questions
  1. BackgroundService 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…

  2. 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…

  3. Since BackgroundService instances are singletons for the app's lifetime, you cannot inject scoped services directly into the constructor -- instead, inject IServiceScopeFactory (or…

  4. 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),…

  5. 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 questions
  1. Blazor 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…

  2. 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…

  3. 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,…

  4. 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…

  5. @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 questions
  1. IMemoryCache 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…

  2. 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…

  3. 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…

  4. Install the Microsoft.Extensions.Caching.StackExchangeRedis package, register it via AddStackExchangeRedisCache with a connection string, then inject IDistributedCache to get/set v…

  5. 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 questions
  1. A typical pipeline includes: restore dependencies (dotnet restore), build (dotnet build), run automated tests (dotnet test), publish deployable artifacts (dotnet publish), and depl…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. The 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. IConfiguration builds a unified key-value configuration tree by combining multiple providers in a specific registration order, where later-registered providers override earlier one…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. CORS (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…

  2. 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-…

  3. 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…

  4. AllowCredentials() permits cross-origin requests to include credentials (cookies, HTTP authentication, client certificates), required for cookie-based authentication to work across…

  5. 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
  1. 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…

  2. 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…

  3. 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…

  4. Calling AddScoped/AddSingleton/AddTransient multiple times for the same interface with different implementations registers all of them; injecting IEnumerable resolves the full coll…

  5. 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
  1. 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…

  2. 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…

  3. 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…

  4. Application Insights (and the vendor-neutral OpenTelemetry standard it increasingly supports) provides distributed tracing (following a single logical request across multiple servi…

  5. 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 questions
  1. The 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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
  1. 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…

  2. 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…

  3. 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…

  4. 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…

  5. `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 questions
  1. The Generic Host (IHost, built via Host.CreateApplicationBuilder or WebApplication.CreateBuilder) provides a unified application startup model handling dependency injection contain…

  2. Host.CreateApplicationBuilder (introduced in .NET 7) is the modern, minimal-hosting-model-aligned builder returning a HostApplicationBuilder with more direct, immediate access to S…

  3. The host registers signal handlers (via IHostApplicationLifetime and platform-specific mechanisms) for graceful shutdown signals -- SIGTERM/SIGINT on Linux/macOS, Ctrl+C or service…

  4. HostApplicationBuilder (and its WebApplicationBuilder subclass) exposes .Configuration (an IConfigurationBuilder pre-populated with the standard providers), .Services (an IServiceC…

  5. 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
  1. Global exception handling middleware catches unhandled exceptions thrown anywhere downstream in the pipeline (controllers, other middleware, business logic), preventing them from c…

  2. IExceptionHandler defines a TryHandleAsync(HttpContext, Exception, CancellationToken) method that you implement as a proper, testable, DI-injectable class rather than an inline del…

  3. 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…

  4. 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…

  5. 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 questions
  1. gRPC 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…

  2. 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…

  3. 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…

  4. 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…

  5. gRPC uses its own set of standardized status codes (like NotFound, InvalidArgument, PermissionDenied, Internal, Unavailable) distinct from HTTP status codes, communicated via gRPC…