.NET
.NET is the open-source, cross-platform platform that combines runtimes, SDKs, languages, libraries, build tooling, package management, diagnostics, and deployment models for modern applications.
Overview
A production .NET system is shaped by distinct choices: the SDK and MSBuild produce assets, the target framework defines compile-time APIs, NuGet resolves dependencies, the runtime loads managed assemblies and executes them through JIT or ahead-of-time compilation, and the publish model decides what ships. Teams must service those layers deliberately, keep builds reproducible, validate configuration, test the published artifact on its target OS and architecture, and use runtime diagnostics before optimizing.
What you will learn
- Distinguish the SDK, CLI, target framework, runtime, host, shared framework, and base class libraries.
- Explain restore, compilation to IL and metadata, assembly loading, JIT execution, garbage collection, and native AOT tradeoffs.
- Create repeatable repositories with global.json, Directory.Build.props, central package management, analyzers, and CI checks.
- Choose framework-dependent, self-contained, single-file, trimmed, native AOT, or container deployment based on operational needs.
- Use configuration, dependency injection, logging, cancellation, async I/O, and diagnostics as platform capabilities.
- Verify package risk, compatibility, publish output, target runtime identifiers, startup, shutdown, and production telemetry.
Prerequisites
- Basic C# syntax and familiarity with projects, solutions, files, processes, and command-line tools.
- The .NET 10 SDK and a terminal; the dedicated sample has no database or external-service dependency.
- Basic awareness of operating systems, CPU architectures, environment variables, and application deployment.
When to use .NET
Good fit
- Cross-platform web, cloud, worker, desktop, mobile, data, tooling, and service applications that benefit from one managed runtime ecosystem.
- Teams that value strong tooling, mature libraries, built-in diagnostics, long-term-support releases, and multiple deployment models.
- Systems that need productive managed code with selective native interop, runtime compilation, trimming, or native AOT options.
Choose another approach when
- A constrained environment where supported .NET runtime or native AOT output cannot meet memory, startup, OS, or architecture limits.
- A platform-mandated codebase whose required native ecosystem, runtime, or ownership makes another stack the safer operational choice.
- Choosing .NET only from synthetic benchmarks without validating expertise, dependencies, deployment, observability, and lifecycle needs.
Key concepts
The SDK supplies compilers, templates, targets, and the dotnet CLI; MSBuild evaluates project files and executes restore, build, test, pack, and publish targets.
A target such as net10.0 selects the compile-time reference API surface; compatibility rules govern referenced projects and packages.
The host selects a compatible runtime, the CLR loads assemblies and manages execution, and shared frameworks provide commonly installed libraries.
Compilers emit intermediate language and metadata; the runtime normally JIT-compiles methods, while native AOT moves more work to publish time.
The garbage collector reclaims managed objects by generation, while IDisposable and await using define deterministic ownership for scarce resources.
Restore resolves direct and transitive packages; central versions, source mapping, lock policy, and audits improve control.
Configuration, logging, dependency injection, options, lifetime, HTTP clients, caching, and telemetry provide common composition primitives.
Framework-dependent, self-contained, single-file, trimmed, AOT, and container outputs have different size, patching, startup, and compatibility implications.
Architecture
The SDK restores packages and uses MSBuild plus language compilers to produce assemblies. Publish combines assemblies with configuration and optional runtime assets. The .NET host selects the runtime, the CLR loads and executes code, and operating-system resources remain explicitly owned.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Create a repeatable repository first, then prove the built and published application on the runtime environment that will own it.
- 01Select and record the toolchain
Choose a supported target framework, record SDK/runtime details, and use global.json when the repository needs deliberate SDK roll-forward behavior.
- 02Centralize repository policy
Use Directory.Build.props for nullable analysis, analyzers, warnings, and build settings, and Directory.Packages.props for reviewed package versions.
- 03Design the project graph
Keep executable entry points, libraries, and tests explicit; enforce dependency direction through project or package references.
- 04Make restore reproducible
Control package sources, centralize versions, use lock policy where needed, cache safely, and fail CI on vulnerable dependencies.
- 05Compose platform services
Load configuration by environment, validate typed options, register owned services, use structured logging, and propagate cancellation.
- 06Choose a publish model
Decide who services the runtime and whether the target requires self-contained, single-file, trimming, AOT, a runtime identifier, or containers.
- 07Verify the artifact
Test Release output, publish from a clean restore, run on each target OS and architecture, exercise shutdown, scan dependencies, and capture diagnostics.
Code example
The dedicated sample combines Generic Host configuration, validated options, dependency injection, logging, and a cancellation-aware application boundary.
var builder = Host.CreateApplicationBuilder(args);
builder.Services
.AddOptions<ProcessingOptions>()
.Bind(builder.Configuration.GetSection(ProcessingOptions.SectionName))
.Validate(o => !string.IsNullOrWhiteSpace(o.InputPath), "InputPath is required.")
.Validate(o => o.MaximumItems is > 0 and <= 10_000, "MaximumItems is invalid.")
.ValidateOnStart();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<IManifestProcessor, ManifestProcessor>();
using var host = builder.Build();
await host.Services.GetRequiredService<IManifestProcessor>()
.ProcessAsync(CancellationToken.None);Testing strategy
Test source behavior and the produced artifact because Debug builds on a developer machine do not prove restore, publish, platform, trimming, or runtime compatibility.
- Run unit and integration tests in Release with the same SDK selection, warning policy, and package graph used by CI.
- Use deterministic seams such as TimeProvider and isolated temporary storage instead of sleep-based or machine-dependent tests.
- Publish from a clean restore and run smoke tests against the output directory rather than only using dotnet run.
- Test every supported OS, architecture, runtime identifier, globalization mode, and deployment model in an appropriate runner or container.
- Enable trimming or native AOT analyzers early and test reflection, serialization, configuration binding, native libraries, and dynamic loading.
Security considerations
The platform boundary includes source feeds, build agents, packages, runtime servicing, configuration, native dependencies, and published artifacts.
- Use trusted NuGet sources, package source mapping where appropriate, dependency review, vulnerability auditing, and controlled private-feed credentials.
- Centrally manage direct packages, review transitive changes, and produce an inventory or SBOM for released artifacts.
- Keep secrets out of project files, appsettings, logs, command histories, and images; use an approved runtime secret provider.
- Patch installed runtimes or rebuild self-contained artifacts promptly when runtime servicing updates are published.
- Use least-privilege OS identities, writable directories, network access, native libraries, and container capabilities.
Performance and scalability
Measure the real workload with runtime diagnostics; allocation, GC, JIT, thread pool, I/O, networking, and dependencies interact.
- Baseline latency, throughput, CPU, working set, allocation, GC pauses, exceptions, thread-pool behavior, and startup before tuning.
- Use dotnet-counters for live signals, dotnet-trace for traces, dotnet-gcdump for managed heaps, and dotnet-dump for failures.
- Prefer asynchronous APIs for concurrent I/O, propagate cancellation, pool expensive connections through supported clients, and dispose scarce resources.
- Benchmark isolated hot paths with representative inputs and Release settings, then confirm gains end to end.
- Evaluate ReadyToRun, tiered compilation, dynamic PGO, trimming, single-file, and native AOT against startup, throughput, size, diagnostics, and compatibility.
Deployment and operations
The deployment model decides artifact contents, compatible targets, runtime servicing ownership, and rollback behavior.
- Framework-dependent deployment uses a compatible installed runtime; self-contained deployment ships one and makes releases responsible for runtime patches.
- Specify and test runtime identifiers only for platform-specific assets; win-x64 output does not run on Linux or Arm64.
- Treat single-file, trimming, ReadyToRun, and native AOT as independent choices with analyzer and runtime verification requirements.
- Build immutable artifacts once, attach provenance and dependency metadata, promote the same artifact, and keep environment configuration external.
- Verify startup, readiness, graceful shutdown, logs, dumps, roll-forward policy, rollback, and runtime version in the target host or container.
Common problems and fixes
The repository builds locally but fails in CI.
Likely cause: SDK selection, workload versions, package sources, cached assets, OS behavior, or warning policy differs.
Fix: Compare dotnet --info, global.json resolution, restore sources, environment variables, and a clean bin/obj-free restore using the CI command.
The published application reports that a framework is missing.
Likely cause: Framework-dependent output reached a host without a compatible shared framework or roll-forward policy.
Fix: Install and service the required runtime, set deliberate roll-forward behavior, or publish self-contained and accept patch ownership.
A trimmed, single-file, or AOT build fails after publishing.
Likely cause: Reflection, dynamic loading, serializers, configuration binding, or native assets were not visible to analysis or packaging.
Fix: Enable publish analyzers, use source generation or annotations, inspect warnings and bundle contents, and add artifact tests.
Memory remains high after work completes.
Likely cause: Live references, caches, large objects, pinned buffers, native memory, or GC policy may retain memory.
Fix: Correlate counters with GC dumps and process metrics, identify retention paths or native owners, then change the measured cause.
Restore resolves an unexpected package or version.
Likely cause: A transitive dependency, central override, floating version, source ordering, cache, or conditional property changed the graph.
Fix: Inspect transitive packages, generated assets, central props, sources, and lock policy; make the intended dependency explicit.
Best practices
- Treat SDK, target framework, runtime, host, and deployment mode as separate versioned decisions.
- Centralize nullable, analyzer, warning, deterministic-build, and package policy.
- Keep restore sources trusted and explicit; audit direct and transitive dependencies.
- Use validated options, structured logging, async I/O, cancellation, and deterministic disposal.
- Publish once and test the Release artifact on every supported OS and architecture.
- Choose deployment mode based on runtime servicing ownership, not convenience alone.
- Enable trimming and AOT analyzers before adopting those modes and verify dynamic features.
- Measure with counters, traces, dumps, and representative benchmarks before tuning.
Production checklist
- The target framework is supported, SDK selection and roll-forward behavior are deliberate, and dotnet --info is captured in CI diagnostics.
- Nullable analysis, analyzers, warnings, deterministic builds, package versions, sources, and vulnerability audits are centrally enforced.
- Release tests and published-artifact smoke tests cover every supported OS, architecture, runtime identifier, and deployment model.
- Configuration is validated at startup, secrets remain external, logs are structured, and cancellation plus graceful shutdown are tested.
- Runtime servicing ownership is explicit for framework-dependent, self-contained, and container deployments.
- Diagnostics can capture counters, traces, dumps, and build/runtime metadata without exposing sensitive data.
- Artifacts are immutable, inventoried, promotable across environments, and covered by rollback procedures.
Common interview questions
What is the difference between the .NET SDK, target framework, and runtime?
The SDK builds applications, the target framework selects compile-time APIs and compatibility rules, and the runtime executes the application. One SDK can target multiple frameworks and a framework-dependent app needs a compatible host runtime.
What does managed code mean?
Managed assemblies execute under the CLR, which provides type loading, exceptions, garbage collection, JIT compilation, diagnostics, and other services; unmanaged resources still require explicit ownership.
Framework-dependent or self-contained deployment?
Framework-dependent output is smaller and relies on a serviced host runtime. Self-contained output includes a runtime but enlarges artifacts and requires application releases for runtime security patches.
How do JIT, ReadyToRun, and native AOT differ?
JIT compiles IL during execution, ReadyToRun precompiles portions while retaining the runtime, and native AOT creates native output at publish time with stricter limits for dynamic code and reflection.
Why use global.json?
It controls SDK selection and roll-forward when a repository needs predictable tool behavior. It does not choose the deployed runtime and must be maintained rather than pinned indefinitely.
How would you investigate high memory in .NET?
Start with process and runtime counters, distinguish managed heap from native and committed memory, capture a GC dump or dump, inspect retention and allocation, then validate the fix under the real workload.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
.NET Platform Baseline
A focused .NET 10 console sample demonstrating SDK selection, centralized build and package policy, Generic Host configuration, validated options, structured logging, async file I/O, cancellation, source-generated JSON, platform inspection, publishing choices, and deterministic tests.
- Run
dotnet run --project src/DotnetPlatformBaseline- Test
dotnet test DotnetPlatformBaseline.slnx