C# Concepts

C# language and base class library concepts explained in depth, one at a time.

Sort

Language Basics

1
Language

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.

2
Language

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::.

3
Language

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.

4
Language

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.

5
Language

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.

6
Language

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

Numbers & Conversions

Operators & Control Flow

Pattern Matching

Exceptions

Methods & Lambdas

Classes & Members

Properties & Initialization

Records & Equality

Inheritance & Polymorphism

Interfaces & Generics

1
Type Design🔬 Lab

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.

2
Type Design🔬 Lab

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).

3
Type Design🔬 Lab

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.

4
Type Design

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).

5
Type Design

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

Nullability

Extension Members

Text & Regex

Common Types

Collections

1
Base Class Library

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.

2
Base Class Library

List<T> and Array Internals

List<T> growth and capacity, array covariance, modifying a collection during foreach, and CollectionsMarshal.AsSpan with its risks.

3
Base Class Library

Dictionary, HashSet, and Equality

Buckets, the Equals and GetHashCode contract, the mutable key bug, IEqualityComparer, and records as keys.

4
Base Class Library

Specialized Collections

Queue, Stack, LinkedList, SortedDictionary vs SortedList, and PriorityQueue (not stable, no priority update).

5
Base Class Library

Immutable and Frozen Collections

ImmutableList vs ImmutableArray, builders, and FrozenDictionary and FrozenSet.

6
Base Class Library

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.

7
Base Class Library

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.

8
Base Class Library🔬 Lab

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

Streams

Networking

Serialization

1
Base Class Library🔬 Lab

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.

2
Base Class Library🔬 Lab

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.

3
Base Class Library

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).

4
Base Class Library

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.

5
Base Class Library

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.

6
Base Class Library

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.

7
Base Class Library

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

1
Base Class Library

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.

2
Base Class Library

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.

3
Base Class Library

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.

4
Base Class Library

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

1
LINQ

LINQ, Deferred Execution, and Iterators

yield return, deferred execution, multiple enumeration, and IEnumerable vs IQueryable as the bridge to EF Core.

2
LINQ🔬 Lab

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.

3
LINQ🔬 Lab

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.

4
LINQ🔬 Lab

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.

5
LINQ

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.

6
LINQ🔬 Lab

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

1
Memory & Concurrency🔬 Lab

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.

2
Memory & Concurrency🔬 Lab

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.

3
Memory & Concurrency

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.

4
Memory & Concurrency🔬 Lab

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.

5
Memory & Concurrency

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.

6
Memory & Concurrency🔬 Lab

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.

7
Memory & Concurrency

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

Threads

What's New