C# Concepts
C# language and base class library concepts explained in depth, one at a time.
Language Basics
C# Language Versions, the Compiler and Preview Features
How the default C# version follows the target framework, how to inspect and override LangVersion, which C# 14 features work on net8.0 and net9.0 and which need a newer runtime, and how LangVersion preview differs from EnablePreviewFeatures.
Top-Level Programs, Implicit Usings and Namespaces
What the compiler generates for a top-level program (Program, <Main>$, the entry-point signatures), the one-file rule, ImplicitUsings per SDK, global using, using static, aliases of any type (C# 12), file-scoped namespaces and resolving name conflicts with an alias or global::.
dynamic, ExpandoObject and the DLR
What dynamic is at compile time and at run time, runtime overload resolution, DLR call sites and their cache with a rough cost measurement, ExpandoObject and DynamicObject, why dynamic JSON via dynamic breaks on JsonElement, and JsonNode as the alternative.
Console Apps, Exit Codes and System.CommandLine
Main signatures, args and the dotnet run -- separator, exit codes and their 0..255 truncation on Unix, crashes and FailFast, stdout versus stderr, stdin and encodings, Ctrl+C and SIGTERM on .NET 10, and a CLI built with System.CommandLine 2.0 and 3.0 (options, arguments, validators, help, parse errors, response files, directives and cancellation), and the .NET 11 FORCE_COLOR support, with the measured exit code of each case.
XML Documentation Comments
How GenerateDocumentationFile produces the XML file and its T:, M: and P: ID strings, cref syntax for generics, overloads and nested types, the real CS1591, CS1570, CS1572, CS1573, CS1574 and CS1587 warnings, inheritdoc and include as the compiler emits them, docs for records, primary constructors and required members, the XML inside a NuGet package, and a build policy that enforces docs without noise.
Preprocessor Directives and Conditional Compilation
The C# preprocessor directives on .NET 10: #define and #if, the symbols the SDK defines (RELEASE yes, WINDOWS no), DefineConstants from MSBuild and the command line, #pragma warning and #nullable, #line, #error and #warning, #region, the #! and #: lines of file-based apps, and the alternatives to #if: runtime OS checks, Conditional, feature switches and static readonly flags.
Strings & Formatting
String Literals: Verbatim, Raw and Escape Sequences
Regular, verbatim, raw and UTF-8 string literals: escape sequences including \e, how raw literals strip indentation and count braces with $$, what a u8 literal really is, and interpolation in constants.
Formatting Values: Interpolated Strings, Format Specifiers and Cultures
The {value,width:format} syntax, what an interpolated string compiles to (handlers and lazy evaluation), the current-culture trap when writing and parsing numbers, IFormattable, ISpanFormattable and CompositeFormat.
Custom Interpolated String Handlers, ISpanFormattable and Format Providers
What the compiler emits for $"..." (IL), writing your own handler with shouldAppend and InterpolatedStringHandlerArgument (logging and parameterized SQL), overload resolution, ISpanFormattable and IUtf8SpanFormattable without allocating, IFormatProvider, ICustomFormatter and who consumes IParsable, measured with BenchmarkDotNet.
Numbers & Conversions
Numeric Types and Binary Representation
Two's complement and shifts (including >>>), IEEE 754 and why 0.1 + 0.2 != 0.3, NaN and Infinity, comparing with a tolerance, the decimal scale, float versus decimal for money, and Half, Int128 and nint.
Numeric Conversions, Rounding and Overflow
Implicit and explicit numeric conversions, what checked and unchecked really change, Math.Round and MidpointRounding (banker's rounding), Convert versus a cast, CheckForOverflowUnderflow and the APIs that pick an overflow policy.
Parsing, TryParse and the Try Pattern
Parse versus TryParse, what the default NumberStyles accept, the reading side of the culture bug with real output, TryParseExact for dates, Enum.TryParse traps, IParsable and ISpanParsable, writing your own Try method and the measured cost of exceptions.
Decimal Floating Point: Decimal32, Decimal64 and Decimal128
The IEEE 754 decimal types of .NET 11 against decimal and double: digits, range, size, BID bits, rounding and silent overflow, conversions, parsing and formatting, System.Text.Json, Complex<T> over the IEEE decimals, measured speed in Release, and an honest note that almost nothing uses them yet.
Operators & Control Flow
Operators, Null Handling and Null-Conditional Assignment
Short-circuit versus eager logical operators, the ?., ?[], ?? and ??= family, and C# 14 null-conditional assignment: what compiles, what does not, the generated code and the nullable analysis.
foreach, the Enumerator Pattern and ref Iteration
How foreach binds to a pattern (GetEnumerator, Current, MoveNext) instead of the interface, the lowering read from the IL for List, arrays, strings and spans, struct enumerators and the boxing measured through IEnumerable, copied enumerators that never move, ref iteration over spans and CollectionsMarshal.AsSpan, and the hidden cast behind an InvalidCastException.
Control Flow: switch, goto and Labeled Jumps
The switch statement and its no-fall-through rule, goto case and goto default, goto with a label, and the C# 15 labeled break and continue (stable on the 11.0.100 SDK), with the real compiler errors and how to choose between a label, a flag and a local function.
Pattern Matching
Pattern Matching: Type, Constant and Relational Patterns, and switch Expressions
The pattern catalog (type, declaration, constant, relational, and/or/not, var, discard), when guards, exhaustiveness and subsumption with the real compiler messages, and the code the compiler generates.
Property, Positional and List Patterns
Extended property patterns, positional patterns through Deconstruct and tuples, list and slice patterns over arrays, lists, spans and strings, what slices allocate, exhaustiveness with sequences, and real uses such as a command parser and a state machine.
Union Types in C# 15: Values From a Closed Set of Types
The C# 15 union declaration, what the compiler generates, patterns that test the contents, the default value and CS8509/CS8655, a hand-written union without boxing (measured at zero bytes), System.Text.Json support and what happens on older target frameworks.
Closed Classes and Exhaustive Hierarchies in C# 15
The C# 15 closed modifier, its rules and real compiler errors, how exhaustiveness is computed over direct subclasses and where it has holes, the metadata the compiler writes, the System.Text.Json default of {} and how closed compares with abstract plus sealed, enum and union.
Exceptions
Exceptions: try, catch, Filters and finally
The two-pass exception model (when filters run before the stack unwinds), catch ordering, what finally guarantees and where it does not run, the measured cost of a throw on .NET 8 and .NET 10, AggregateException, ExceptionDispatchInfo, process-wide handlers and how to design a custom exception.
Guard Clauses, Throwing and Rethrowing
Usage errors versus execution errors, the ThrowIf helpers from .NET 6 to 8, CallerArgumentExpression for your own guards, throw helpers and inlining shown in JIT output, DoesNotReturn and nullable analysis, guards in async methods, and throw; versus throw ex; versus wrapping.
Result Types versus Exceptions
When to throw, when to use a Try method and when to return a Result, decided by the kind of failure; a minimal Result<T> with the traps of a hand-written one (default as success), composition with Bind, measured cost, mapping to ProblemDetails at the HTTP boundary, and what OneOf and ErrorOr look like.
Methods & Lambdas
Method Parameters: Optional, Named and ref Kinds
Default values compiled into the caller (with a reproduced binary break and the IL that explains it), named arguments, overload resolution in practice, ref, out, in and C# 12 ref readonly, and the defensive copies made for structs that are not readonly.
Local Functions, Lambdas and Closures
The lowering of lambdas and local functions read from the IL (display class, cached delegate, struct closure), measured allocations, where a closure is created, static lambdas, natural types and defaults, C# 14 parameter modifiers without types, and when to prefer a local function.
Tuples and Deconstruction
What a tuple is at run time (ValueTuple, a mutable struct with public fields, Auto layout, Rest above seven elements), where element names go (TupleElementNames, reflection and the {} from System.Text.Json), == versus Equals, tuples as dictionary keys, the deconstruction forms, instance and extension Deconstruct, the legacy System.Tuple, and when a record is the better choice.
Classes & Members
Classes, Members and Access Modifiers
Defaults and rules for type and member accessibility, protected internal versus private protected, the protected qualifier rule, InternalsVisibleTo, the file modifier, and the members every class inherits from System.Object.
Fields, Constants and Initialization Order
Instance and static initialization order with real output, virtual calls in constructors, const versus static readonly across assemblies, beforefieldinit, and required members with SetsRequiredMembers.
Enums and Flags Enums
An enum is an integer with names, not a closed set: underlying type and size, the zero value, [Flags] and bit operations, the HasFlag traps, validating values from outside, switching over an enum, generic code, and when to replace an enum with something else.
Partial Types and Partial Members
How partial declarations merge, legacy versus extended partial methods, partial properties and indexers (C# 13), partial constructors and events (C# 14), and the contract with source generators.
Operator Overloading and User-Defined Conversions
Operators as static methods, the pairs the compiler enforces, implicit and explicit conversions, checked operators (C# 11), and the C# 14 instance compound assignment and increment operators, which mutate in place and change what x += y means for a reference type.
Properties & Initialization
Properties, init Accessors and the field Keyword
What the compiler generates for a property, what init guarantees and what it does not, and the exact rules of the C# 14 field keyword: binding, the upgrade break, field-targeted attributes, nullable analysis, and partial properties.
Primary Constructors for Classes and Structs
Primary constructor parameters become hidden, mutable fields when a member uses them: the generated IL, the CS9124 and CS9107 double-storage warnings, getting readonly and validation back, and the struct rules.
Indexers and Index/Range Support
How indexers are declared and compiled, ref returning indexers, the exact pattern the compiler uses to enable ^ and .., List<T> ranges since .NET 8, which slices copy and which do not, and the edge cases that throw.
Records & Equality
Records and with Expressions
What the compiler generates for a record, read from the IL (EqualityContract, PrintMembers, the clone method, Deconstruct), record class versus record struct, why with is a shallow copy, inheritance, and where records fit (DTOs, JSON) and where they do not (EF Core entities).
Struct and Record Equality
The equality defaults of classes, structs, records, tuples, and arrays side by side, the weak hash of a plain struct, implementing IEquatable<T> on a struct, customizing record equality for collection members, and keeping Equals symmetric in a class hierarchy.
Inheritance & Polymorphism
Interfaces & Generics
Interfaces: Explicit Implementation and Default Methods
Implicit vs explicit implementation and when explicit is required, default interface methods (C# 8) and the diamond, static abstract and static virtual members (C# 11), and IComparable, IComparer and IEquatable.
Generics: Constraints and Variance
Why generics replaced object-based collections (boxing measured), reified generics, constraints up to allows ref struct (C# 13), value-type specialization vs shared reference-type code seen in the JIT, constraints that avoid boxing, out/in variance, covariant arrays, and generic attributes (C# 11).
Generic Math and static abstract Interface Members
The .NET 7 generic math interfaces built on C# 11 static abstract members: picking the smallest constraint for a generic Sum, plugging your own type in, integer division and overflow in generic code (checked operators), the machine code the JIT emits, how Enumerable.Sum uses it, and what the compiler refuses.
Design Patterns with Pattern Matching, Unions and DI
Strategy, Decorator, State and Visitor rewritten in today's C# (delegates, keyed services, Scrutor, switch over a closed record hierarchy), what each costs in ns and bytes, the private-constructor simulation of a closed union, and what C# 15 union and closed change (docs only).
Legacy Interfaces: ICloneable, ISerializable and Friends
ICloneable and the shallow copy trap, ISerializable, [Serializable] and BinaryFormatter today, what Exception still serializes, which serializer honors which hook, ArrayList and Hashtable against the generics, IAsyncResult and the APM pattern, with a measured book-versus-today note on .NET 10.
Delegates & Events
Delegates and Multicast Invocation
What the compiler generates for a delegate type, Target and Method, Func, Action and Predicate vs custom delegate types, immutable invocation lists with += and -= (right-most removal), an exception in the middle of a multicast, EnumerateInvocationList (.NET 9), method group caching (C# 11) and function pointers (C# 9).
Events, the Observer Pattern and Memory Leaks
What event restricts compared with a delegate field, the add/remove accessors with Interlocked.CompareExchange the compiler generates (lost subscriptions measured), EventHandler<TEventArgs> and raising with ?.Invoke, the long-lived publisher leak measured with WeakReference and the GC, unsubscribing, weak events, custom accessors and C# 14 partial events.
Nullability
Extension Members
Extension Methods and Fluent APIs
The classic this syntax and what the compiler emits, why the type's own members always win, compile-time binding by static type (and not with dynamic), which namespace wins, extensions over interfaces and generics, null and ref receivers, mutable versus immutable fluent APIs, the IServiceCollection.AddX convention and the Reverse trap.
Extension Members and Extension Blocks (C# 14)
C# 14 extension(Type receiver) blocks with instance methods and properties, static methods and properties and operators, generic blocks, null and ref receivers, what the compiler emits (grouping and marker types read with ilspy), a binary compatibility test against the this syntax, ambiguity and how to resolve it, and what is not allowed, with the real compiler errors.
Text & Regex
Strings: Comparison, Culture and Ordering
Ordinal vs cultural comparison, StringComparison, StringComparer and CompareOptions, .NET 10 NumericOrdering, invariant globalization mode, and string immutability and interning.
Regular Expressions in Depth
The backtracking and NonBacktracking engines, options that change a pattern's meaning, named groups, lookaround, greedy vs lazy, EnumerateMatches and match timeouts.
Generated Regex and ReDoS
GeneratedRegex on partial methods and properties, interpreted vs compiled vs generated (measured), fallbacks, SYSLIB1040-1045 analyzers, and ReDoS defenses with match timeouts.
Building and Searching Strings Efficiently
StringBuilder versus concatenation in loops, string.Create and spans, ArrayPool, SearchValues for vectorized search (substrings since .NET 9), and measuring before optimizing.
Unicode, Runes and Text Encodings
char, Rune and grapheme clusters, UTF-8/16/32, invalid bytes and the BOM, legacy code pages, and Base64, Base64Url (.NET 9) and hex.
Common Types
Random Numbers, GUIDs and UUID v7
Random and Random.Shared, Shuffle and GetItems, RandomNumberGenerator for security, Guid.CreateVersion7 (.NET 9) and what sortable really guarantees for database keys.
Dates, Times and Time Zones
DateTime and DateTimeKind, round-trip formats, DateTimeOffset, TimeZoneInfo with IANA and Windows ids and invariant mode, daylight saving gaps and repeated hours with 23 and 25 hour days, the recurring 9 am meeting bug, DateOnly and TimeOnly, DateTimeStyles, TimeProvider with FakeTimeProvider, and Stopwatch.
Collections
Collection Interfaces and Choosing a Collection
IEnumerable, ICollection, IList and the read-only interfaces, how to pick parameter and return types, collection expressions, and what a read-only view does not guarantee.
List<T> and Array Internals
List<T> growth and capacity, array covariance, modifying a collection during foreach, and CollectionsMarshal.AsSpan with its risks.
Dictionary, HashSet, and Equality
Buckets, the Equals and GetHashCode contract, the mutable key bug, IEqualityComparer, and records as keys.
Specialized Collections
Queue, Stack, LinkedList, SortedDictionary vs SortedList, and PriorityQueue (not stable, no priority update).
Immutable and Frozen Collections
ImmutableList vs ImmutableArray, builders, and FrozenDictionary and FrozenSet.
Collections Gap Audit: OrderedDictionary and ReadOnlySet
OrderedDictionary<TKey,TValue> (.NET 9, index overloads in .NET 10), ReadOnlySet<T>, EnsureCapacity on Queue, Stack and PriorityQueue, and the audit of the existing collections concepts.
Comparing and Sorting: IComparable and IComparer
The sign contract of IComparable and IComparer, Comparison and Comparer.Default, nulls, the exceptions for a missing or inconsistent comparison, why CompareTo must agree with Equals in SortedSet and BinarySearch, unstable List.Sort versus stable OrderBy, multi-key ordering, BinarySearch insertion points, NaN and DateTimeOffset, span sorting and the measured cost of each comparer style.
Collection Expressions, Spread and with(...) Arguments in C# 15
Collection expressions from C# 12 to 15: the concrete type the compiler picks per target, spread, CollectionBuilder, the C# 15 with(...) arguments (capacity, comparer), their real compiler errors, and the silent change of a method named with, checked on the 11.0.100 SDK.
Files & I/O
File System APIs and Cross-Platform Paths
Path.Join versus Path.Combine, OS differences, FileMode/FileShare/FileOptions, lazy enumeration, symbolic links, safe file replacement, and RandomAccess with File.OpenHandle.
Compression: ZIP, GZip, Brotli and Tar
GZip, Deflate, ZLib and Brotli as stream decorators, what CompressionLevel really buys, ZipArchive in memory and on disk with the .NET 10 async APIs, tar, zip slip, and capping decompressed size.
Running External Processes with Process
Process and ProcessStartInfo with ArgumentList, the stdout and stderr deadlock and its fix, timeout with Kill(entireProcessTree), exit codes and signals, and the .NET 11 shortcuts (Run, RunAndCaptureText, ReadAllLines, ProcessExitStatus) with their timeout behavior checked.
Binary Data: Endianness, BinaryReader and Memory-Mapped Files
BinaryWriter and BinaryReader byte by byte (7-bit string prefix, always little-endian), endianness with BinaryPrimitives, a real file header with StructLayout and MemoryMarshal, MemoryMappedFile (access modes, Flush, view pointer, sequential and random reads measured) and System.IO.Hashing (Crc32, Crc64, XxHash3) against SHA256 and MD5, with the bridge to virtual memory and the page cache.
Streams
Stream Class Hierarchy and Decorators
Stream, FileStream, MemoryStream and BufferedStream, decorators like GZipStream, leaveOpen, short reads and ReadExactly.
Async I/O and System.IO.Pipelines
ReadAsync and CopyToAsync, ArrayPool<byte>, and PipeReader and PipeWriter with backpressure.
Async Streams with IAsyncEnumerable
await foreach, EnumeratorCancellation, and streaming JSON from ASP.NET Core.
Networking
TCP and UDP Sockets, Named Pipes and QUIC in .NET
Socket, TcpListener and TcpClient, TCP as a byte stream with length-prefix framing, NoDelay, backlog, close and reset, timeouts, UDP, named pipes, Unix domain sockets, System.Net.Quic and the .NET 11 QuicStream.Priority, measured on loopback.
DNS Resolution and the DnsResolver API
Dns.GetHostEntryAsync and what it does not do (OS getaddrinfo, no SRV, TXT, TTL or server choice), the typed .NET 11 DnsResolver, SRV priority and weight as service discovery, NXDOMAIN, timeouts and the lack of a cache, measured against a local CoreDNS.
Serialization
System.Text.Json: Serialization and Options
Why JsonSerializerOptions must be reused (with the measured cost of a fresh converter), what JsonSerializerDefaults.Web and the .NET 10 Strict preset change, naming policies, JsonIgnoreCondition, numbers and enums, [JsonDerivedType] polymorphism, required members, constructor parameters and null handling.
System.Text.Json: Source Generation, JsonNode and Utf8JsonReader
JsonSerializerContext and [JsonSerializable], what trimming and AOT analyzers actually flag (without publishing AOT), JsonDocument versus JsonNode versus a typed read measured, Utf8JsonReader and Utf8JsonWriter, and streaming arrays with DeserializeAsyncEnumerable.
JSON Converters, Contract Customization and Schema Export
JsonConverter<T> and JsonConverterFactory, null handling and registration precedence, contract customization with modifiers, and what JsonSchemaExporter describes (and cannot see behind a custom converter).
Migrating from Newtonsoft.Json to System.Text.Json
The behavior differences measured by running the same input through both libraries (casing, comments, numbers, dates, ignored attributes, fields, object and the DOM), how to configure System.Text.Json for each, and a test-driven migration order.
BinaryFormatter Removal and Safe Serialization
What the runtime does since .NET 9, why the format is unsafe by design (CWE-502), the mechanism shown with a harmless class, alternatives (System.Text.Json, protobuf-net), and reading old payloads with NrbfDecoder.
XML Serialization and LINQ to XML
XmlSerializer and DataContractSerializer (what they include and silently skip), namespace and encoding surprises, querying and editing with LINQ to XML, streaming with XmlReader, and the parser settings that decide whether hostile XML can read files or exhaust memory.
CBOR and Compact Binary Formats
System.Formats.Cbor (CborWriter and CborReader) with the bytes in hex, the same object in JSON, CBOR, MessagePack and Protobuf, conformance modes and key order, .NET 11 incremental reading and a COSE_Sign1 message signed and verified, with the passkey bridge.
Reflection & Attributes
Attributes: Custom and Compiler-Read
Declaring an attribute with AttributeUsage and the compile errors of its rules, targets such as assembly, return and field, reading attributes by reflection and what each lookup costs, Inherited on overrides, the attributes the compiler interprets (caller info, Conditional, Obsolete, Experimental, nullability, ModuleInitializer, SetsRequiredMembers, InlineArray) and a command dispatcher with its trimming warnings.
Reflection: Type Metadata and Its Costs
typeof, GetType and Type.GetType, the BindingFlags traps, private members, Activator and Invoke with ref and out, TargetInvocationException, generics, NullabilityInfoContext and ReflectionTypeLoadException, the measured cost against delegates and UnsafeAccessor, and what breaks under trimming and Native AOT.
Writing a Roslyn Analyzer and an Incremental Source Generator
A DiagnosticAnalyzer for DateTime.Now against TimeProvider, choosing between syntax, operation and symbol actions, a code fix with DocumentEditor and FixAll, tests with Microsoft.CodeAnalysis.Testing, NuGet packaging, severity through .editorconfig and an IIncrementalGenerator whose incremental cache is measured with a GeneratorDriver.
Debugging Attributes and Visualizing Types
DebuggerDisplay, DebuggerBrowsable, DebuggerTypeProxy, the step and hide attributes and StackTraceHidden, read with CustomAttributeData, their effect on StackTrace, Debugger, Debug.Assert and Trace without a debugger, and what dotnet-dump ignores.
LINQ
LINQ, Deferred Execution, and Iterators
yield return, deferred execution, multiple enumeration, and IEnumerable vs IQueryable as the bridge to EF Core.
LINQ: Operator Families and Query Syntax
The LINQ operator families, how the compiler rewrites query syntax (let, into, transparent identifiers), and stable ordering with ThenBy, Order() and culture-aware string comparison.
LINQ: Sets, Joins, Grouping and Lookups
Set semantics and the By variants, Join, GroupJoin and the .NET 10 LeftJoin and RightJoin, null keys, GroupBy versus ToLookup, and the SQL EF Core generates for each.
Expression Trees and IQueryable Providers
Expression<Func<>> versus a delegate, what the compiler refuses to put in a tree, how Queryable and IQueryProvider cooperate, why captured variables become SQL parameters, and dynamic filters with ExpressionVisitor that keep the query cache.
LINQ: Aggregation, Paging and Chunking
What each aggregate does with an empty sequence, the Sum accumulator and overflow, Aggregate, MinBy and MaxBy, Any versus Count, Skip, Take and Take(Range), Chunk, and how paging behaves in memory and through EF Core 10.
Writing LINQ Operators and How LINQ Is Implemented
How to write an operator in LINQ's style (eager validation, separate iterator, generic math), the specialized iterators .NET 10 picks per source type, TryGetNonEnumeratedCount, span fast paths, OrderBy().First() without sorting, vectorized Sum, and what a pipeline allocates.
Memory & Value Semantics
Value Types, Reference Types and Boxing
Copy semantics versus location, why "structs live on the stack" is a half-truth, struct layout and padding, mutable struct bugs from invisible copies, where boxing hides (Equals, GetHashCode, interface enumerators, Nullable) and how to measure allocations on .NET 10.
Span, Memory and Slicing Without Allocating
What a Span<T> is, slicing versus Substring and array ranges, C# 14 implicit span conversions and their upgrade surprises, the ref struct rules, stackalloc with an ArrayPool fallback, scoped, params spans, inline arrays, Memory<T> across await and MemoryMarshal.
IDisposable, Finalizers and Deterministic Cleanup
using statements and declarations, await using and IAsyncDisposable, the dispose pattern and when it is needed, the measured cost of a finalizer, why SafeHandle replaces almost every finalizer, and how the DI container disposes services on .NET 10.
The Garbage Collector: Generations and the LOH
Generations 0, 1 and 2 and promotion, the large and pinned object heaps, workstation versus server GC, background GC and DATAS, container limits, what changed in .NET 10, GC.Collect myths and the tools to measure, with numbers from .NET 10.
GC Tuning: Server, Workstation, Concurrent and No-GC Regions
Workstation against Server, background GC, GCSettings.LatencyMode, GC.TryStartNoGCRegion, DATAS, GCConserveMemory, GCHeapCount and container heap limits, measured with a stress program on macOS and a Linux Docker VM.
Benchmarking with BenchmarkDotNet and Allocation Profiling
Why a Stopwatch misleads, BenchmarkDotNet with MemoryDiagnoser, baselines, Ratio and parameters, reading the report, the traps (dead code elimination, setup, Debug), .NET 10 against .NET 11, ArrayPool and ObjectPool measured, and dotnet-counters for allocation in a running process, with numbers from one machine.
SIMD in .NET: Vector<T>, Vector128/256/512 and Hardware Intrinsics
Why the JIT does not vectorize a plain loop, Vector<T> and Vector128/256/512 with a scalar remainder, masks and ConditionalSelect, the IsHardwareAccelerated dispatch pattern, AdvSimd on Apple Silicon, byte count, find and array sum measured against LINQ, span.Count, IndexOf and TensorPrimitives, the float and out-of-bounds pitfalls, and the .NET 11 lane operations (docs only).
Interop & Unsafe
P/Invoke, LibraryImport and Native Interop
DllImport versus the LibraryImport source generator and the stub it emits, calling libc and a clang-built dylib, library names and entry points, UTF-8 versus UTF-16, errno with SetLastError, the bool size trap, struct layout and Pack, spans and pinning, callbacks collected by the GC, NativeLibrary and import resolvers, native memory and SafeHandle, all run on macOS arm64.
Unsafe Code, Pointers and Function Pointers
Enabling unsafe code and the CS0227 error, pointer operators and scaled arithmetic, fixed for arrays, strings and spans, fixed-size buffers versus InlineArray, Unsafe, MemoryMarshal and NativeMemory, a measured overrun and a stale pointer after GC compaction, function pointers with UnmanagedCallersOnly and measured call costs, the safe replacements and the C# 15 memory safety model.
Threads
Threads, the ThreadPool, and Starvation
Thread, foreground vs background, thread injection, starvation from sync-over-async, and LongRunning.
Locks, Monitor, and Interlocked
lock and Monitor, System.Threading.Lock, Interlocked, ReaderWriterLockSlim, and why await cannot be used inside lock.
Memory Model, volatile, and Thread-Local State
volatile and Volatile.Read, double-checked locking vs Lazy<T>, and ThreadLocal vs AsyncLocal.
Synchronization Primitives: Barrier, CountdownEvent, SpinLock and Events
Barrier and its post-phase action, CountdownEvent as fork/join without Task, ManualResetEventSlim and AutoResetEvent with spinning, SpinLock as a struct, ReaderWriterLockSlim and when a plain lock or an immutable snapshot wins, and System.Threading.Lock, all measured, with the bridge to operating systems semaphores and spin locks.
Dataflow Pipelines: TPL Dataflow and Rx
TPL Dataflow blocks, LinkTo, BoundedCapacity backpressure, EnsureOrdered, fault and cancellation, Rx.NET cold and hot sources, schedulers, the undisposed subscription, Task.WhenEach and .NET 10 async LINQ, with Channel, Dataflow, Rx and Parallel.ForEachAsync measured on one job.
What's New
What's New in C# 14: A Map of the Features
A navigation map of the C# 14 features that ship with .NET 10: extension members, the field keyword, null-conditional assignment, implicit span conversions, unbound nameof, lambda parameter modifiers, partial constructors and events, and user-defined compound assignment, each with a short summary and a link to the deep concept.
What's New in C# 15: A Map of the Features
A navigation map of the C# 15 features that ship with .NET 11: collection expression arguments, union types, closed classes, extension indexers, labeled break and continue, static interface members on older runtimes and the memory safety model that is still preview, each with a compiled snippet, the C# 14 error and a link to the deep concept, plus what did not make it into C# 15.