C# 14 features
What actually shipped in C# 14, with code.
This pillar indexes everything I’ve written about C# 14 language features: extension members, partial constructors and events, the field keyword, user-defined compound assignment, and the smaller ergonomic wins that are easy to miss in the official release notes.
What to read first
For the headline 14.0 features, C# 14 Extension Members and Partial constructors and events in C# 14 are the biggest behavioural changes if you’re coming from C# 12. After that, C# 14 user-defined compound assignment operators and the field keyword cover the perf-sensitive bits.
What’s on this page
The list below auto-collects posts tagged with any of: c# 14, csharp 14, csharp-14, c#, csharp, c# language. Newest first.
Index (143 posts)
2026 / 05
- .NET 11 Adds Deadlock-Free Process Output Capture
.NET 11 Preview 4 ships new System.Diagnostics.Process APIs that drain stdout and stderr concurrently, plus one-line run-and-capture helpers and KillOnParentExit.
- Fix: A possible object cycle was detected
System.Text.Json refuses to serialize graphs with back-references. Set ReferenceHandler.IgnoreCycles, project to a DTO, or mark the back-pointer with [JsonIgnore]. Preserve is a last resort.
- Fix: SqlException: Timeout expired during EF Core migrations
Migrations use the design-time DbContext, not your runtime CommandTimeout. Set the timeout via UseSqlServer(o => o.CommandTimeout(...)), the connection string Command Timeout, or Database.SetCommandTimeout before Migrate().
- Fix: System.Text.Json.JsonException: The JSON value could not be converted
System.Text.Json throws this when the incoming JSON token doesn't match the CLR target type. Match the JSON to the type, or register a JsonConverter or JsonSerializerOption that bridges them.
- Fix: System.Security.Cryptography.CryptographicException: Keyset does not exist
The certificate's private key lives in a separate Windows key file the current process identity cannot read. Grant ACL on the key, load the PFX with MachineKeySet, or use EphemeralKeySet.
- Fix: System.IO.FileNotFoundException: Could not load file or assembly in a published app
Runs fine with dotnet run, throws after dotnet publish. The DLL is usually missing from the publish folder, not the runtime. Check deps.json, ProjectReference Private, and trimming.
- Fix: InvalidOperationException: Synchronous operations are disallowed
Replace the Stream.Read or Write call with ReadAsync/WriteAsync. As a last resort, set AllowSynchronousIO on Kestrel, IIS, or per-request via IHttpBodyControlFeature.
- Fix: RZ10012: Found markup element with unexpected name in Blazor
Blazor's Razor compiler emits RZ10012 when a PascalCase tag has no matching component type in scope. Add @using for the component's namespace in _Imports.razor, or @namespace in the component, then rebuild.
- Fix: dotnet ef migrations add fails with 'Unable to create an object of type DbContext'
EF Core's design-time tools could not instantiate your DbContext. Either expose a host via WebApplication.CreateBuilder, point to the right startup project, or implement IDesignTimeDbContextFactory.
- Fix: MSB3027 Could not copy X to Y. Exceeded retry count of 10. Failed
MSB3027 means MSBuild retried a file copy 10 times and a process still held the destination. Kill the locking process, exclude bin/obj from antivirus, or raise CopyRetryCount.
- Fix: The type or namespace name 'X' could not be found (after adding a project reference)
CS0246 right after a fresh ProjectReference is almost always a TargetFramework mismatch, a stale obj folder, or a missing using directive. Five fixes in order of likelihood.
- Fix: Cannot consume scoped service 'X' from singleton 'Y'
ASP.NET Core's scope validation throws this when a singleton would capture a scoped dependency for the rest of the process. Make the consumer scoped, or take IServiceScopeFactory and create a scope on demand.
- Fix: PlatformNotSupportedException: Operation is not supported on this platform in Native AOT
Native AOT strips the JIT and the interpreter, so reflection emit, expression-tree compilation, and unseen MakeGenericType throw at runtime. Find the call via IL3050 and replace it with a source generator or a pre-baked path.
- Fix: Unable to resolve service for type 'X' while attempting to activate 'Y'
ASP.NET Core throws this when a constructor asks for a type that was never registered, was registered on the wrong container, or was added after the host was built. Three concrete fixes cover almost every case.
- Fix: TaskCanceledException: A task was canceled in HttpClient
HttpClient throws TaskCanceledException for three different reasons: timeout, caller cancellation, or a connection-level abort. Tell them apart with InnerException and CancellationToken.IsCancellationRequested, then fix the right one.
- Fix: The JSON value could not be converted to System.DateTime
System.Text.Json only accepts ISO 8601 strings for DateTime. Send 2026-05-08T14:00:00Z or register a JsonConverter that parses your format. Empty strings and Unix timestamps both throw.
- Microsoft Agent Framework workflows now survive process restarts via the Durable Task stack
Wrap an Agent Framework Workflow in Microsoft.Agents.AI.DurableTask and each executor step is checkpointed. Crash, redeploy, restart - the run continues where it stopped.
- Fix: The instance of entity type cannot be tracked because another instance with the same key value is already being tracked
EF Core 11 throws when two objects share a primary key inside one DbContext. Detach the old one or update it in place. AsNoTracking on the read prevents the collision.
- Fix: A second operation was started on this context instance before a previous operation completed
EF Core throws when two awaits run in parallel on the same DbContext. Await each call sequentially, or get a new DbContext per concurrent unit of work via IDbContextFactory.
- Microsoft Agent Framework gates risky tool calls behind FunctionApprovalRequestContent
Wrap an AIFunction in ApprovalRequiredAIFunction and the agent stops mid-run to ask permission. Here is how the request and response flow works in C#.
- How to Run a Semantic Kernel Plugin From a BackgroundService
Wire a Microsoft.SemanticKernel 1.75.0 plugin into a hosted BackgroundService on .NET 11 and invoke its KernelFunctions on a PeriodicTimer schedule. Covers DI scopes, [KernelFunction] resolution, prompt-cache-friendly invocation, cancellation, and the lifetime gotchas that bite when you move a plugin off the request path.
- Fix: System.InvalidOperationException: No connection string named 'DefaultConnection' could be found
If GetConnectionString returns null in .NET 11, your appsettings.json is missing the key, not copied to the build output, or the wrong environment file is being selected. Three checks fix 95% of cases.
- How to Expose an EF Core Database to an AI Agent via MCP
Wire an EF Core 10 DbContext into a Model Context Protocol server so Claude Code, Cursor, or any compliant client can run safe, scoped queries against your database. Covers IDbContextFactory lifetime, read-only projections, schema discovery tools, AsNoTracking, parameterised filters, row-level scoping, and the destructive-tool gates you need before letting an agent touch UPDATE.
- How to convert T[] to ReadOnlyMemory<T> in C# (implicit operator and explicit constructor)
Three ways to wrap a T[] in a ReadOnlyMemory<T> in .NET 11: the implicit conversion, the explicit constructor, and AsMemory(). When each is the right call.
- How to Add Tool Calling to a Microsoft.Extensions.AI Chat Client
Wire AIFunctionFactory.Create, ChatOptions.Tools, and ChatClientBuilder.UseFunctionInvocation in Microsoft.Extensions.AI 10.5 so an IChatClient can call your .NET methods automatically. Covers OpenAI and Azure OpenAI providers, the FunctionInvokingChatClient knobs that actually matter (iteration limits, concurrent calls, approval prompts, error handling), and streaming responses with tools.
- How to implement drag-and-drop in .NET MAUI 11
End-to-end drag-and-drop in .NET MAUI 11: DragGestureRecognizer, DropGestureRecognizer, custom DataPackage payloads, AcceptedOperation, gesture position, and the per-platform PlatformArgs traps on Android, iOS, Mac Catalyst, and Windows.
- How to support dark mode correctly in a .NET MAUI app
End-to-end dark mode in .NET MAUI 11: AppThemeBinding, SetAppThemeColor, RequestedTheme, UserAppTheme override with persistence, the RequestedThemeChanged event, and the per-platform Info.plist and MainActivity bits that the docs gloss over.
- How to use Tailwind CSS with Blazor WebAssembly in .NET 11
A complete .NET 11 setup for Tailwind CSS v4 in a Blazor WebAssembly app: standalone CLI (no Node), MSBuild target, @source directives for Razor and CSS isolation files, and a publish pipeline that survives Native AOT.
- How to detect N+1 queries in EF Core 11
A practical guide to spotting N+1 queries in EF Core 11: what the pattern looks like in real code, how to surface it via logging, diagnostic interceptors, OpenTelemetry, and a test that fails the build when a hot path regresses.
- How to use compiled queries with EF Core for hot paths
A practical guide to EF Core 11 compiled queries: when EF.CompileAsyncQuery actually wins, the static-field pattern, the Include and tracking gotchas, and how to benchmark before and after so you can prove it was worth the extra ceremony.
- How to write a MAUI app that runs on Windows and macOS only (no mobile)
Strip Android and iOS from a .NET MAUI 11 project so it ships Windows and Mac Catalyst only: the csproj edits, the workload commands, and the multi-targeting that keeps your code clean.
- How to Migrate a Semantic Kernel Plugin to an MCP Server
Take an existing Semantic Kernel plugin with [KernelFunction] methods and turn it into a Model Context Protocol server other agents can call. Covers the drop-in WithTools(kernel) bridge, the native [McpServerTool] rewrite, parameter binding, dependency injection, and the gotchas that bite during the cutover.
- How to set up structured logging with Serilog and Seq in .NET 11
A complete guide to wiring Serilog 4.x and Seq 2025.2 into a .NET 11 ASP.NET Core app: AddSerilog vs UseSerilog, two-stage bootstrap logging, JSON configuration, enrichers, request logging, OpenTelemetry trace correlation, API keys, and the production gotchas around buffering, retention, and signal level.
- How to use OpenTelemetry with .NET 11 and a free backend
Wire OpenTelemetry traces, metrics, and logs into a .NET 11 ASP.NET Core app with the OTLP exporter, then ship them to a free, self-hosted backend: the standalone Aspire Dashboard for local dev, Jaeger and SigNoz for self-hosted production, and the OpenTelemetry Collector when you need both.
- How to write integration tests against a real SQL Server with Testcontainers
A complete guide to running ASP.NET Core integration tests against a real SQL Server 2022 using Testcontainers 4.11 and EF Core 11: WebApplicationFactory wiring, IAsyncLifetime, swapping the DbContext registration, applying migrations, parallelism, Ryuk cleanup, and CI gotchas.
2026 / 04
- How to add per-endpoint rate limiting in ASP.NET Core 11
A complete guide to per-endpoint rate limiting in ASP.NET Core 11: when to pick fixed window vs sliding window vs token bucket vs concurrency, how RequireRateLimiting and [EnableRateLimiting] differ, partitioning by user or IP, the OnRejected handler, and the distributed deployment pitfall everyone hits.
- How to use the new System.Threading.Lock type in .NET 11
System.Threading.Lock arrived in .NET 9 and is the default synchronization primitive on .NET 11 and C# 14. This guide shows how to migrate from lock(object), how EnterScope works, and the gotchas around await, dynamic, and downlevel targets.
- How to write a source generator for INotifyPropertyChanged
A complete guide to building your own incremental source generator for INotifyPropertyChanged in C# 14 and .NET 11: the IIncrementalGenerator pipeline, marker attributes, partial-class output, the SetProperty pattern, and how to stay AOT-friendly.
- How to detect when a file finishes being written to in .NET
FileSystemWatcher fires Changed before the writer is done. Three reliable patterns for .NET 11 to know a file is fully written: open with FileShare.None, debounce with size stabilization, and the producer-side rename trick that avoids the problem entirely.
- How to share validation logic between server and Blazor WebAssembly
The single biggest source of validation drift in a Blazor WebAssembly + ASP.NET Core app is the urge to write the rules twice. This guide walks the only layout that scales in .NET 11: a Shared class library that owns the DTOs and their validators, consumed by both the WASM client (EditForm + DataAnnotationsValidator or Blazored.FluentValidation) and the server (minimal API endpoint filter or MVC model binding), with a tested round-trip that maps server-side ValidationProblemDetails back into the EditContext.
- How to use SearchValues<T> correctly in .NET 11
SearchValues<T> beats IndexOfAny by 5x to 250x but only when you use it the way the runtime expects. The cache-as-static rule, the StringComparison gotcha, when not to bother, and the IndexOfAnyExcept inversion trick that nobody documents.
- How to use Native AOT with ASP.NET Core minimal APIs
A complete .NET 11 walkthrough for shipping an ASP.NET Core minimal API with Native AOT: PublishAot, CreateSlimBuilder, source-generated JSON, the AddControllers limitation, IL2026 / IL3050 warnings, and EnableRequestDelegateGenerator for library projects.
- How to warm up EF Core's model before the first query
EF Core builds its conceptual model lazily on the first DbContext access, which is why the first query in a fresh process is several hundred milliseconds slower than every query after it. This guide covers the three real fixes in EF Core 11: a startup IHostedService that touches Model and opens a connection, dotnet ef dbcontext optimize to ship a precompiled model, and the cache-key footguns that silently rebuild the model anyway.
- How to add a global exception filter in ASP.NET Core 11
A complete guide to global exception handling in ASP.NET Core 11: why IExceptionFilter is the wrong tool, how IExceptionHandler and UseExceptionHandler work together, ProblemDetails responses, multi-handler chains, and the .NET 10 diagnostics suppression breaking change.
- How to Build a Custom MCP Server in C# on .NET 11
Build a working Model Context Protocol server in C# 14 / .NET 11 using the official ModelContextProtocol 1.2 SDK. Covers stdio transport, [McpServerTool] attributes, dependency injection, the stderr logging trap, and registration with Claude Code, Claude Desktop, and VS Code.
- How to mock DbContext without breaking change tracking
Mocking DbContext directly silently breaks ChangeTracker, which is why Microsoft discourages it. This guide shows the two patterns that actually work in EF Core 11: SQLite in-memory with a kept-open connection so the real ChangeTracker runs, and the repository pattern that lifts EF Core out of the test entirely.
- How to unit-test code that uses HttpClient
A complete guide to testing HttpClient in .NET 11: why you should not mock HttpClient directly, how to write a stub HttpMessageHandler, swapping the primary handler with IHttpClientFactory, verifying Polly retries, and the WireMock.Net option.
- How to use Channels instead of BlockingCollection in C#
System.Threading.Channels is the async-first replacement for BlockingCollection in .NET 11. This guide shows how to migrate, how to choose bounded vs unbounded, and how to handle backpressure, cancellation, and graceful shutdown without deadlocking.
- How to write a custom JsonConverter in System.Text.Json
A complete guide to writing custom JsonConverter<T> for System.Text.Json in .NET 11: when you actually need one, how to navigate Utf8JsonReader correctly, how to handle generics with JsonConverterFactory, and how to stay AOT-friendly.
- How to Generate Strongly Typed Client Code from an OpenAPI Spec in .NET 11
Use Kiota, Microsoft's official OpenAPI code generator, to produce a fluent, strongly typed C# client from any OpenAPI spec. Step-by-step: install, generate, wire into ASP.NET Core DI, and handle authentication.
- How to read a large CSV in .NET 11 without running out of memory
Stream a multi-gigabyte CSV in .NET 11 without OutOfMemoryException. File.ReadLines, CsvHelper, Sylvan, and Pipelines compared with code and measurements.
- How to cancel a long-running Task in C# without deadlocking
Cooperative cancellation with CancellationToken, CancelAsync, Task.WaitAsync, and linked tokens in .NET 11. Plus the blocking patterns that turn a clean cancel into a deadlock.
- How to use IAsyncEnumerable<T> with EF Core 11
EF Core 11 queries implement IAsyncEnumerable<T> directly. Here is how to stream rows with await foreach, when to prefer it over ToListAsync, and the gotchas around connections, tracking, and cancellation.
- How to use records with EF Core 11 correctly
A practical guide to mixing C# records and EF Core 11. Where records fit, where they break change tracking, and how to model value objects, entities, and projections without fighting the framework.
- Node.js Addons in C#: .NET Native AOT Replaces C++ and node-gyp
The C# Dev Kit team swapped its C++ Node.js addon for a .NET 10 Native AOT library, using N-API, UnmanagedCallersOnly, and LibraryImport to produce a single .node file without Python or node-gyp.
- How to return multiple values from a method in C# 14
Seven ways to return more than one value from a C# 14 method: named tuples, out parameters, records, structs, deconstruction, and the extension-member trick for types you don't own. Real benchmarks and a decision matrix at the end.
- RyuJIT trims more bounds checks in .NET 11 Preview 3: index-from-end and i + constant
.NET 11 Preview 3 teaches RyuJIT to eliminate redundant bounds checks on consecutive index-from-end access and on i + constant < length patterns, cutting branch pressure in tight loops.
- RegexOptions.AnyNewLine lands in .NET 11 Preview 3: Unicode-aware anchors without the \r? hacks
.NET 11 Preview 3 adds RegexOptions.AnyNewLine so ^, $, \Z, and . recognize every Unicode newline sequence, including \r\n, NEL, LS, and PS, with \r\n treated as one atomic break.
- EF Core 11 Prunes Unnecessary Reference Joins in Split Queries
EF Core 11 Preview 3 removes redundant to-one joins from split queries and drops unneeded ORDER BY keys. One reported scenario got 29% faster, another 22%. Here is what the SQL now looks like.
- System.Text.Json in .NET 11 Preview 3 adds PascalCase and per-member naming policies
.NET 11 Preview 3 finishes the naming-policy story in System.Text.Json: JsonNamingPolicy.PascalCase, a member-level [JsonNamingPolicy] attribute, and a type-level [JsonIgnore] default for cleaner DTOs.
- EF Core 11 Adds GetEntriesForState to Skip DetectChanges
EF Core 11 Preview 3 introduces ChangeTracker.GetEntriesForState, a state-filtered enumerator that avoids an extra DetectChanges pass in hot paths like SaveChanges interceptors and audit hooks.
- Building a Microsecond-Latency Database Engine in C#
Loic Baumann's Typhon project targets 1-2 microsecond ACID commits using ref structs, hardware intrinsics, and pinned memory, proving C# can compete at the systems programming level.
- C# 14 user-defined compound assignment operators: in-place += without the extra allocation
C# 14 lets you overload +=, -=, *=, and friends as void instance methods that mutate the receiver in place, cutting allocations for large value holders like BigInteger-style buffers and tensors.
- How Dapper's Default nvarchar Parameters Silently Kill Your SQL Server Indexes
C# strings sent through Dapper default to nvarchar(4000), forcing SQL Server into implicit conversions and full index scans. Here's how to fix it with DbType.AnsiString.
- .NET 11 Adds Native Zstandard Compression to System.IO.Compression
.NET 11 Preview 1 ships ZstandardStream, ZstandardEncoder, and ZstandardDecoder in System.IO.Compression, giving you fast, inbox zstd support with no third-party packages.
- EF Core 11 Lets You Create and Apply a Migration in One Command
The dotnet ef database update command now accepts --add to scaffold and apply a migration in a single step. Here is how it works, why it matters for containers and .NET Aspire, and what to watch for.
- EF Core 11 Adds Native SQL Server Vector Search with DiskANN Indexes
EF Core 11 Preview 2 supports SQL Server 2025 VECTOR_SEARCH() and DiskANN vector indexes directly from LINQ. Here is how to set up the index, run approximate queries, and what changes from the EF Core 10 VectorDistance approach.
- ReSharper Lands in VS Code and Cursor, Free for Non-Commercial Use
JetBrains shipped ReSharper as a VS Code extension with full C# analysis, refactoring, and unit testing. It works in Cursor and Google Antigravity too, and costs nothing for OSS and learning.
- C# 15 Union Types Are Here: Type Unions Ship in .NET 11 Preview 2
C# 15 introduces the union keyword for type unions with exhaustive pattern matching and implicit conversions. Available now in .NET 11 Preview 2.
- Microsoft Agent Framework 1.0: Building AI Agents in Pure C#
Microsoft Agent Framework hits 1.0 with stable APIs, multi-provider connectors, multi-agent orchestration, and A2A/MCP interop. Here is what it looks like in practice on .NET 10.
- .NET 11 Runtime Async Replaces State Machines with Cleaner Stack Traces
Runtime Async in .NET 11 moves async/await handling from compiler-generated state machines into the runtime itself, producing readable stack traces, correct breakpoints, and fewer heap allocations.
2026 / 02
- C# 14 Extension Members: Extension Properties, Operators, and Static Extensions
C# 14 introduces extension members, allowing you to add extension properties, operators, and static members to existing types using the new extension keyword.
- C# 14 idea: interceptors could make System.Text.Json source generation feel automatic
A community discussion proposed using C# 14 interceptors to rewrite JsonSerializer calls so they automatically use a generated JsonSerializerContext, keeping AOT-friendly source generation with cleaner call sites.
- C# 14 Null-Conditional Assignment: Using ?. and ?[] on the Left Side
C# 14 extends null-conditional operators to work on the left-hand side of assignments, eliminating verbose null checks when setting properties or indexers.
- Polars.NET: a Rust DataFrame engine for .NET 10 that leans on LibraryImport
A new Polars.NET project is trending after a Feb 6, 2026 community post. The headline is simple: a .NET-friendly DataFrame API backed by Rust Polars, with a stable C ABI and LibraryImport-based interop to keep overhead low.
2026 / 01
- A WinUI 3 “local-only notes” app is the right kind of boring: offline-first, SQLite, keyboard-first
Miyanyedi Quick Note is a WinUI 3 + SQLite note-taking app that is offline-first and privacy-friendly. Here is why local-only is a feature, plus a minimal SQLite snippet for .NET 8 desktop apps.
- CV Shortlist: an AI-powered .NET 10 SaaS went open-source, and the stack is worth studying
CV Shortlist is an open-source .NET 10 SaaS that pairs Azure Document Intelligence with an OpenAI model. The stack, config discipline, and AI integration boundary are worth studying.
- ModularPipelines V3: write CI pipelines in C#, debug locally, stop babysitting YAML
ModularPipelines V3 lets you write CI pipelines in C# instead of YAML. Run them locally with dotnet run, get compile-time safety, and debug with breakpoints.
- Microsoft `mcp`: Wiring Model Context Protocol Servers from C# on .NET 10
How to wire Model Context Protocol (MCP) servers in C# on .NET 10 using microsoft/mcp. Covers tool contracts, input validation, auth, observability, and production-readiness patterns.
- C# 13: The End of `params` Allocations
C# 13 finally eliminates the hidden array allocation behind params. You can now use params with Span, ReadOnlySpan, List, and other collection types for zero-allocation variadic methods.
- C# Proposal: Discriminated Unions
A look at the C# discriminated unions proposal: the union keyword, exhaustive pattern matching, and how it could replace OneOf libraries and class hierarchies.
2025 / 04
- C# 14: Simplified parameters with modifiers in lambdas
C# 14 allows using ref, out, in, scoped, and ref readonly modifiers on implicitly typed lambda parameters, eliminating the need to explicitly declare parameter types.
- Partial constructors and events in C# 14
C# 14 lets you declare instance constructors and events as partial members, splitting definitions across files for cleaner code generation and separation of concerns.
- C# 14: nameof support for unbound generic types
C# 14 enhances the nameof expression to support unbound generic types like List<> and Dictionary<,>, eliminating the need for placeholder type arguments.
- Implicit Span conversions in C# 14 – First-class support for Span and ReadOnlySpan
C# 14 adds built-in implicit conversions between Span, ReadOnlySpan, arrays, and strings, enabling cleaner APIs, better type inference, and fewer manual AsSpan() calls.
- C# 14 – The field keyword and field-backed properties
C# 14 introduces the field contextual keyword for property accessors, letting you add custom logic to auto-properties without declaring a separate backing field.
2025 / 01
- .NET Performance: ToList vs ToArray
.NET 9 significantly improves ToArray performance using InlineArray, making it faster and more memory-efficient than ToList. See benchmarks comparing .NET 8 vs .NET 9.
- C# 13: Use params collections with any recognized collection type
C# 13 extends the params modifier beyond arrays to support Span, ReadOnlySpan, IEnumerable, and other collection types, reducing boilerplate and improving flexibility.
- How to switch to C# 13
How to fix 'Feature is not available in C# 12.0' and switch your project to C# 13 by changing the target framework or setting LangVersion in your .csproj file.
2024 / 12
- C# language version history
The evolution of C# has transformed it into a modern, high-performance language. This guide tracks every major milestone. The Early Years (C# 1.0 – 1.2) C# launched in 2002 as a primary language for the .NET Framework. It felt like Java but with a focus on Windows development. Version 1.2 arrived shortly after with small…
- What’s new in C# 14.0
A summary of all new features in C# 14.0, including the field keyword, extension members, null-conditional assignment, implicit span conversions, and more.
2023 / 11
- C# Randomly choose items from a list
In C#, you can randomly select items from a list using Random.GetItems, a method introduced in .NET 8. Learn how it works with practical examples.
- MAUI: How to register handlers in a library
Learn how to register view handlers and services from within a .NET MAUI library using the builder pattern and MauiAppBuilder extension methods.
- How to fix: ‘Point’ does not have a predefined size, therefore sizeof can only be used in an unsafe context
Fix the C# error where sizeof cannot be used with Point outside an unsafe context. Two solutions: enabling unsafe code or using Marshal.SizeOf instead.
- C# Access private property backing field using Unsafe Accessor
Use UnsafeAccessorAttribute in .NET 8 to access auto-generated backing fields of private auto-properties in C# without reflection.
- C# ZIP files to Stream
.NET 8 includes new CreateFromDirectory and ExtractToDirectory overloads that let you create and extract ZIP files directly to and from a Stream, without writing to disk.
- .NET 8 performance: 10x faster GetGenericTypeDefinition
Benchmarking GetGenericTypeDefinition in .NET 8 vs .NET 7 shows nearly 10x faster performance. See benchmark code and results using BenchmarkDotNet.
- How to take a screenshot in .NET core
Learn how to capture a screenshot of your entire desktop from a .NET console application using System.Windows.Forms. Windows-only solution covering all displays.
- C# How to update a readonly field using UnsafeAccessor
Learn how to update a readonly field in C# using UnsafeAccessor, an alternative to reflection without the performance penalty. Available in .NET 8.
- .NET 8 Performance: UnsafeAccessor vs. Reflection
Benchmarking UnsafeAccessor vs Reflection in .NET 8. See how UnsafeAccessor achieves zero-overhead performance compared to traditional reflection.
2023 / 10
- C# – How to mark features as experimental
Starting with C# 12, a new ExperimentalAttribute lets you mark types, methods, properties, or assemblies as experimental. Learn how to use it with diagnosticId, pragma tags, and UrlFormat.
- C# – ref readonly parameters
The ref readonly modifier in C# provides a more transparent way of passing read-only references. Learn how it improves on the in modifier with better constraints and caller visibility.
- C# – How to shuffle an array?
The easiest way to shuffle an array in C# is using Random.Shuffle, introduced in .NET 8. It works in-place on both arrays and spans.
- C# – What is a NullReferenceException, and how to fix it?
Learn what causes a NullReferenceException in C#, how to debug it, and how to prevent it using null checks, the null-conditional operator, and nullable reference types.
- Add/Remove TypeInfoResolver to existing JsonSerializerOptions
Learn how to add or remove TypeInfoResolver instances on existing JsonSerializerOptions using the new TypeInfoResolverChain property in .NET 8.
- C# 12 – Interceptors
Learn about C# 12 interceptors, an experimental .NET 8 compiler feature that lets you replace method calls at compile time using the InterceptsLocation attribute.
2023 / 09
- Implementation type Data.AppDbContext can’t be converted to service type Microsoft.AspNetCore.Identity.IUserStore
Fix the ASP.NET Core Identity error where AppDbContext can't be converted to IUserStore by adding AddEntityFrameworkStores to your identity configuration.
- .NET 8 – Serializing properties from interface hierarchies
.NET 8 adds support for serializing properties from interface hierarchies, including all properties from all interfaces depending on the declared variable type.
- .NET 8 – Deserialize into non-public properties
Learn how to deserialize JSON into non-public properties in .NET 8 using the JsonInclude attribute and parameterized constructors.
- .NET 8 – How to use JsonStringEnumConverter with native AOT
Learn how to use the new JsonStringEnumConverter<TEnum> in .NET 8 for native AOT-compatible enum serialization with System.Text.Json.
- The type or namespace name InterceptsLocationAttribute could not be found
How to fix error CS0246 for InterceptsLocationAttribute in C# interceptors by defining the attribute yourself.
- .NET 8 – Mark JsonSerializerOptions as readonly
Learn how to mark JsonSerializerOptions instances as read-only in .NET 8 using MakeReadOnly, and how to check the IsReadOnly property.
- .NET 8 – Serialization of Half, Int128, and UInt128
System.Text.Json in .NET 8 adds built-in serialization support for the Half, Int128, and UInt128 numeric types.
- .NET 8 – Memory<byte> is serialized as base64
Starting with .NET 8, both Memory<byte> and ReadOnlyMemory<byte> are serialized as Base64 strings, while other types like Memory<int> remain JSON arrays.
- .NET 8 – Include non-public members in JSON serialization
Learn how to include private, protected, and internal properties in JSON serialization in .NET 8 using the JsonInclude attribute.
2023 / 08
- C# 12 – Inline arrays
Inline arrays enable you to create an array of fixed size in a struct type. Such a struct, with an inline buffer, should provide performance comparable to an unsafe fixed size buffer. Inline arrays are mostly to be used by the runtime team and some library authors to improve performance in certain scenarios. You likely…
- C# 12 – Collection expressions
C# 12 introduces a new simplified syntax for creating arrays. It looks like this: It’s important to note that the array type needs to be specified explicitly, so you cannot use var for declaring the variable. Similarly, if you wanted to create a Span<int>, you can do: Multi-dimensional arrays The advantages of this terse syntax…
- C# How to wait for a process to end?
You can use the WaitForExit method to wait for the process to complete. Your code will wait synchronously for the process to finish, then it will resume execution. Let’s look at an example: The code above will start a new cmd.exe process, and execute the timeout 5 command. The process.WaitForExit() call will force your program…
- C# 12 – Alias any type
The using alias directive has been relaxed in C# 12 to allow aliasing any sort of type, not just named types. This means that you can now alias tuples, pointers, array types, generic types, etc. So instead of using the full structural form of a tuple, you can now alias it with a short descriptive…
- Is there a C# With…End With statement equivalent?
The With…End With statement in VB allows you to execute a series of statements that repeatedly refer to a single object. Thus the statements can use a simplified syntax for accessing members of the object. For example: Is there a C# syntax equivalent? No. There is not. The closest thing to it would be the…
2023 / 07
- C# 12 – Primary constructors
Starting from C# 12, it is possible to define a primary constructor within classes and structs. The parameters are placed in parentheses right after the type name. The parameters of a primary constructor have a broad scope. They can be utilized to initialize properties or fields, serve as variables in methods or local functions, and…
2023 / 06
- How to start programming with C#
A beginner's guide to getting started with C# programming, from setting up Visual Studio to writing your first program and finding learning resources.
- What’s new in C# 12
An overview of new features in C# 12, including primary constructors, default lambda parameters, collection expressions, inline arrays, and more.
- How to switch to C# 12
Fix C# 12 language version errors by updating your target framework to .NET 8 or setting LangVersion in your .csproj file.
2023 / 05
- C# 12 – Default values for parameters in lambda expressions
C# 12 lets you specify default parameter values and params arrays in lambda expressions, just like in methods and local functions.
2023 / 03
- C# 11 – Generic attributes
Learn how to define and use generic attributes in C# 11, including restrictions on type arguments and common error messages.
- C# 11 – file access modifier & file-scoped types
Learn how the C# 11 file access modifier restricts a type's scope to the file in which it is declared, helping avoid name collisions with source generators.
- C# 11 – Interpolated raw string literal
Learn how to use interpolated raw string literals in C# 11, including escaping braces, multiple $ characters, and conditional operators.
- C# 11 raw string literals (triple-quote syntax)
Use C# 11 raw string literals (triple-quote `"""` syntax) to embed whitespace, newlines, and quotes without escape sequences. Rules and examples.
- How to switch to C# 11
Fix the 'Feature is not available in C# 10.0' error by switching to C# 11 via target framework or LangVersion in your .csproj file.
- C# throw if null: ArgumentNullException.ThrowIfNull (.NET 6+)
Use ArgumentNullException.ThrowIfNull in .NET 6+ for concise null checks, or use throw expressions in C# 7+ for older frameworks.
2020 / 11
- Get Embedded Resource Stream in .NET Core
Learn how to retrieve an embedded resource stream in .NET Core by understanding how resource names are composed and using GetManifestResourceStream.
- How to use appsettings.json with Xamarin.Forms
Learn how to use appsettings.json configuration files with Xamarin.Forms by embedding the file as a resource and building an IConfiguration object.
- How to publicly expose your local SignalR service for consumption by mobile clients using ngrok
Use ngrok to publicly expose your local SignalR service so mobile clients can connect without network configuration or SSL workarounds.
2020 / 05
- C# using var (using declaration)
Use C# 8 `using var` declarations to dispose IDisposable objects without nested braces. Syntax, scope rules, and when to prefer `using` blocks instead.
2020 / 04
- C# 8.0 Null-coalescing assignment ??=
Learn how the C# 8.0 null-coalescing assignment operator (??=) works, with practical examples including caching and conditional assignment.
2019 / 01
- Animating backgrounds with Xamarin Forms
Create a smooth animated background effect in Xamarin Forms using ScaleTo animations on layered BoxViews.
2013 / 10
- How long does it take a PC to count to one trillion
Benchmarking how long it takes a PC to count to one trillion and beyond, with updated results from 2023.
2013 / 06
- Adding speech recognition to your WP8 app
Add speech recognition to your Windows Phone 8 app using the SpeechTextBox control from the Windows Phone toolkit.
- Periodically update your live tiles using ScheduledTaskAgent
Use a ScheduledTaskAgent to periodically update your Windows Phone live tiles from an RSS feed.
2013 / 05
- Creating wide tiles for your Windows Phone 7 app
Create wide live tiles for both Windows Phone 7 and 8 using the MangoPollo library with a single piece of code.
2012 / 01
- C# Convert Hex To Color
A C# extension method that converts hex color codes (both RGB and ARGB formats) to Color objects.
- Improve productivity by using code snippets
Learn how code snippets in Visual Studio can improve your productivity by letting you insert reusable pieces of code with a short alias.