dotnet-csharp-modern-patterns
Modern C# language feature guidance adapted to the project's target framework. Always run
[skill:dotnet-version-detection] first to determine TFM and C# version.
Scope
- Records, pattern matching, primary constructors, collection expressions
- C# 12-15 feature usage mapped to TFM
- Language feature adoption guidance
Out of scope
- Naming and style conventions -- see [skill:dotnet-csharp-coding-standards]
- Async/await patterns -- see [skill:dotnet-csharp-async-patterns]
- Source generator usage (GeneratedRegex, LoggerMessage) -- see [skill:dotnet-csharp-source-generators]
Cross-references: [skill:dotnet-csharp-coding-standards] for naming/style conventions,
[skill:dotnet-csharp-async-patterns] for async-specific patterns.
Quick Reference: TFM to C# Version
| TFM |
C# |
Key Language Features |
| net8.0 |
12 |
Primary constructors, collection expressions, alias any type |
| net9.0 |
13 |
params collections, Lock type, partial properties |
| net10.0 |
14 |
field keyword, extension blocks, nameof unbound generics |
| net11.0 |
15 (preview) |
Collection expression with() arguments |
Records
Use records for immutable data transfer objects, value semantics, and domain modeling where equality is based on values
rather than identity.
Record Classes (reference type)
// Positional record: concise, immutable, value equality
public record OrderSummary(int OrderId, decimal Total, DateOnly OrderDate);
// With additional members
public record Customer(string Name, string Email)
{
public string DisplayName => $"{Name} <{Email}>";
}
```text
### Record Structs (value type, C# 10+)
```csharp
// Positional record struct: value type with value semantics
public readonly record struct Point(double X, double Y);
// Mutable record struct (rare -- prefer readonly)
public record struct MutablePoint(double X, double Y);
```text
### When to Use Records vs Classes
| Use Case | Prefer |
| ------------------------------------ | ------------------------ |
| DTOs, API responses | `record` |
| Domain value objects (Money, Email) | `readonly record struct` |
| Entities with identity (User, Order) | `class` |
| High-throughput, small data | `readonly record struct` |
| Inheritance needed | `record` (class-based) |
### Non-destructive Mutation
```csharp
var updated = order with { Total = order.Total + tax };
```csharp
---
## Primary Constructors (C# 12+, net8.0+)
Capture constructor parameters directly in the class/struct body. Parameters become available throughout the type but
are **not** fields or properties -- they are captured state.
### For Services (DI injection)
```csharp
public class OrderService(IOrderRepository repo, ILogger<OrderService> logger)
{
public async Task<Order> GetAsync(int id)
{
logger.LogInformation("Fetching order {OrderId}", id);
return await repo.GetByIdAsync(id);
}
}
```text
### Gotchas
- Primary constructor parameters are **mutable** captures, not `readonly` fields. If immutability matters, assign to a
`readonly` field in the body.
- Do not use primary constructors when you need to validate parameters at construction time -- use a traditional
constructor with guard clauses instead.
- For records, positional parameters become public properties automatically. For classes/structs, they remain private
captures.
```csharp
// Explicit readonly field when immutability matters
public class Config(string connectionString)
{
private readonly string _connectionString = connectionString
?? throw new ArgumentNullException(nameof(connectionString));
}
```text
---
## Collection Expressions (C# 12+, net8.0+)
Unified syntax for creating collections with `[...]`.
```csharp
// Array
int[] numbers = [1, 2, 3];
// List
List<string> names = ["Alice", "Bob"];
// Span
ReadOnlySpan<byte> bytes = [0x00, 0xFF];
// Spread operator
int[] combined = [..first, ..second, 99];
// Empty collection
List<int> empty = [];
```text
### Collection Expression with Arguments (C# 15 preview, net11.0+)
Specify capacity, comparers, or other constructor arguments:
```csharp
// Capacity hint
List<int> nums = [with(capacity: 1000), ..Generate()];
// Custom comparer
HashSet<string> set = [with(comparer: StringComparer.OrdinalIgnoreCase), "Alice", "bob"];
// Dictionary with comparer
Dictionary<string, int> map = [with(comparer: StringComparer.OrdinalIgnoreCase),
new("key1", 1), new("key2", 2)];
```text
> **net11.0+ only.** Requires `<LangVersion>preview</LangVersion>`. Do not use on earlier TFMs.
---
## Pattern Matching
### Switch Expressions (C# 8+)
```csharp
string GetDiscount(Customer customer) => customer switch
{
{ Tier: "Gold", YearsActive: > 5 } => "30%",
{ Tier: "Gold" } => "20%",
{ Tier: "Silver" } => "10%",
_ => "0%"
};
```text
### List Patterns (C# 11+)
```csharp
bool IsValid(int[] data) => data is [> 0, .., > 0]; // first and last positive
string Describe(int[] values) => values switch
{
[] => "empty",
[var single] => $"single: {single}",
[var first, .., var last] => $"range: {first}..{last}"
};
```text
### Type and Property Patterns
```csharp
decimal CalculateShipping(object package) => package switch
{
Letter { Weight: < 50 } => 0.50m,
Parcel { Weight: var w } when w < 1000 => 5.00m + w * 0.01m,
Parcel { IsOversized: true } => 25.00m,
_ => 10.00m
};
```text
---
## `required` Members (C# 11+)
Force callers to initialize properties at construction via object initializers.
```csharp
public class UserDto
{
public required string Name { get; init; }
public required string Email { get; init; }
public string? Phone { get; init; }
}
// Compiler enforces Name and Email
var user = new UserDto { Name = "Alice", Email = "alice@example.com" };
```text
Useful for DTOs that need to be deserialized (System.Text.Json honors `required` in .NET 8+).
---
## `field` Keyword (C# 14, net10.0+)
Access the compiler-generated backing field directly in property accessors.
```csharp
public class TemperatureSensor
{
public double Reading
{
get => field;
set => field = value >= -273.15
? value
: throw new ArgumentOutOfRangeException(nameof(value));
}
}
```text
Replaces the manual pattern of declaring a private field plus a property with custom logic. Use when you need validation
or transformation in a setter without a separate backing field.
> **net10.0+ only.** On earlier TFMs, use a traditional private field.
---
## Extension Blocks (C# 14, net10.0+)
Group extension members for a type in a single block.
```csharp
public static class EnumerableExtensions
{
extension<T>(IEnumerable<T> source) where T : class
{
public IEnumerable<T> WhereNotNull()
=> source.Where(x => x is not null);
public bool IsEmpty()
=> !source.Any();
}
}
```text
> **net10.0+ only.** On earlier TFMs, use traditional `static` extension methods.
---
## Alias Any Type (`using`, C# 12+, net8.0+)
```csharp
using Point = (double X, double Y);
using UserId = System.Guid;
Point origin = (0, 0);
UserId id = UserId.NewGuid();
```text
Useful for tuple aliases and domain type aliases without creating a full type.
---
## `params` Collections (C# 13, net9.0+)
`params` now supports additional collection types beyond arrays, including `Span<T>`, `ReadOnlySpan<T>`, and types
implementing certain collection interfaces.
```csharp
public void Log(params ReadOnlySpan<string> messages)
{
foreach (var msg in messages)
Console.WriteLine(msg);
}
// Callers: compiler may avoid heap allocation with span-based params
Log("hello", "world");
```text
> **net9.0+ only.** On net8.0, `params` only supports arrays.
---
## `Lock` Type (C# 13, net9.0+)
Use `System.Threading.Lock` instead of `object` for locking.
```csharp
private readonly Lock _lock = new();
public void DoWork()
{
lock (_lock)
{
// thread-safe operation
}
}
```text
`Lock` provides a `Scope`-based API for advanced scenarios and is more expressive than `lock (object)`.
> **net9.0+ only.** On net8.0, use `private readonly object _gate = new();` and `lock (_gate)`.
---
## Partial Properties (C# 13, net9.0+)
Partial properties enable source generators to define property signatures that users implement, or vice versa.
```csharp
// In generated file
public partial class ViewModel
{
public partial string Name { get; set; }
}
// In user file
public partial class ViewModel
{
private string _name = "";
public partial string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
}
```text
> **net9.0+ only.** See [skill:dotnet-csharp-source-generators] for generator patterns.
---
## `nameof` for Unbound Generic Types (C# 14, net10.0+)
```csharp
string name = nameof(List<>); // "List"
string name2 = nameof(Dictionary<,>); // "Dictionary"
```csharp
Useful in logging, diagnostics, and reflection scenarios.
> **net10.0+ only.**
---
## Polyfill Guidance for Multi-Targeting
When targeting multiple TFMs, newer language features may not compile on older targets. Use these approaches:
1. **PolySharp** -- Polyfills compiler-required types (`IsExternalInit`, `RequiredMemberAttribute`, etc.) so language
features like `init`, `required`, and `record` work on older TFMs.
2. **Polyfill** -- Polyfills runtime APIs (e.g., `string.Contains(char)` for netstandard2.0).
3. **Conditional compilation** -- Use `#if` for features that cannot be polyfilled:
```csharp
#if NET10_0_OR_GREATER
// Use field keyword
public double Value { get => field; set => field = Math.Max(0, value); }
#else
private double _value;
public double Value { get => _value; set => _value = Math.Max(0, value); }
#endif
```text
See [skill:dotnet-multi-targeting] for comprehensive polyfill guidance.
---
## Knowledge Sources
Feature guidance in this skill is grounded in publicly available language design rationale from:
- **C# Language Design Notes (Mads Torgersen et al.)** -- Design decisions behind each C# version's features. Key
rationale relevant to this skill: primary constructors (reducing boilerplate for DI-heavy services), collection
expressions (unifying collection initialization syntax), `field` keyword (eliminating backing field ceremony), and
extension blocks (grouping extensions by target type). Each feature balances expressiveness with safety -- e.g.,
primary constructor parameters are intentionally mutable captures (not readonly) to keep the feature simple; use
explicit readonly fields when immutability is needed. Source: https://github.com/dotnet/csharplang/tree/main/meetings
- **C# Language Proposals Repository** -- Detailed specifications and design rationale for accepted and proposed
features. Source: https://github.com/dotnet/csharplang/tree/main/proposals
> **Note:** This skill applies publicly documented design rationale. It does not represent or speak for the named
> sources.
## References
- [C# Language Reference](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/)
- [What's new in C# 12](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12)
- [What's new in C# 13](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-13)
- [What's new in C# 14](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-14)
- [C# Language Design Notes](https://github.com/dotnet/csharplang/tree/main/meetings)
- [.NET Framework Design Guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/)
1---2name: dotnet-csharp-modern-patterns-23description: Using records, pattern matching, primary constructors, collection expressions. C# 12-15 by TFM.4---5# dotnet-csharp-modern-patterns67Modern C# language feature guidance adapted to the project's target framework. Always run8[skill:dotnet-version-detection] first to determine TFM and C# version.910## Scope1112- Records, pattern matching, primary constructors, collection expressions13- C# 12-15 feature usage mapped to TFM14- Language feature adoption guidance1516## Out of scope1718- Naming and style conventions -- see [skill:dotnet-csharp-coding-standards]19- Async/await patterns -- see [skill:dotnet-csharp-async-patterns]20- Source generator usage (GeneratedRegex, LoggerMessage) -- see [skill:dotnet-csharp-source-generators]2122Cross-references: [skill:dotnet-csharp-coding-standards] for naming/style conventions,23[skill:dotnet-csharp-async-patterns] for async-specific patterns.2425---2627## Quick Reference: TFM to C# Version2829| TFM | C# | Key Language Features |30| ------- | ------------ | ------------------------------------------------------------ |31| net8.0 | 12 | Primary constructors, collection expressions, alias any type |32| net9.0 | 13 | `params` collections, `Lock` type, partial properties |33| net10.0 | 14 | `field` keyword, extension blocks, `nameof` unbound generics |34| net11.0 | 15 (preview) | Collection expression `with()` arguments |3536---3738## Records3940Use records for immutable data transfer objects, value semantics, and domain modeling where equality is based on values41rather than identity.4243### Record Classes (reference type)4445````csharp4647// Positional record: concise, immutable, value equality48public record OrderSummary(int OrderId, decimal Total, DateOnly OrderDate);4950// With additional members51public record Customer(string Name, string Email)52{53 public string DisplayName => $"{Name} <{Email}>";54}5556```text5758### Record Structs (value type, C# 10+)5960```csharp6162// Positional record struct: value type with value semantics63public readonly record struct Point(double X, double Y);6465// Mutable record struct (rare -- prefer readonly)66public record struct MutablePoint(double X, double Y);6768```text6970### When to Use Records vs Classes7172| Use Case | Prefer |73| ------------------------------------ | ------------------------ |74| DTOs, API responses | `record` |75| Domain value objects (Money, Email) | `readonly record struct` |76| Entities with identity (User, Order) | `class` |77| High-throughput, small data | `readonly record struct` |78| Inheritance needed | `record` (class-based) |7980### Non-destructive Mutation8182```csharp8384var updated = order with { Total = order.Total + tax };8586```csharp8788---8990## Primary Constructors (C# 12+, net8.0+)9192Capture constructor parameters directly in the class/struct body. Parameters become available throughout the type but93are **not** fields or properties -- they are captured state.9495### For Services (DI injection)9697```csharp9899public class OrderService(IOrderRepository repo, ILogger<OrderService> logger)100{101 public async Task<Order> GetAsync(int id)102 {103 logger.LogInformation("Fetching order {OrderId}", id);104 return await repo.GetByIdAsync(id);105 }106}107108```text109110### Gotchas111112- Primary constructor parameters are **mutable** captures, not `readonly` fields. If immutability matters, assign to a113 `readonly` field in the body.114- Do not use primary constructors when you need to validate parameters at construction time -- use a traditional115 constructor with guard clauses instead.116- For records, positional parameters become public properties automatically. For classes/structs, they remain private117 captures.118119```csharp120121// Explicit readonly field when immutability matters122public class Config(string connectionString)123{124 private readonly string _connectionString = connectionString125 ?? throw new ArgumentNullException(nameof(connectionString));126}127128```text129130---131132## Collection Expressions (C# 12+, net8.0+)133134Unified syntax for creating collections with `[...]`.135136```csharp137138// Array139int[] numbers = [1, 2, 3];140141// List142List<string> names = ["Alice", "Bob"];143144// Span145ReadOnlySpan<byte> bytes = [0x00, 0xFF];146147// Spread operator148int[] combined = [..first, ..second, 99];149150// Empty collection151List<int> empty = [];152153```text154155### Collection Expression with Arguments (C# 15 preview, net11.0+)156157Specify capacity, comparers, or other constructor arguments:158159```csharp160161// Capacity hint162List<int> nums = [with(capacity: 1000), ..Generate()];163164// Custom comparer165HashSet<string> set = [with(comparer: StringComparer.OrdinalIgnoreCase), "Alice", "bob"];166167// Dictionary with comparer168Dictionary<string, int> map = [with(comparer: StringComparer.OrdinalIgnoreCase),169 new("key1", 1), new("key2", 2)];170171```text172173> **net11.0+ only.** Requires `<LangVersion>preview</LangVersion>`. Do not use on earlier TFMs.174175---176177## Pattern Matching178179### Switch Expressions (C# 8+)180181```csharp182183string GetDiscount(Customer customer) => customer switch184{185 { Tier: "Gold", YearsActive: > 5 } => "30%",186 { Tier: "Gold" } => "20%",187 { Tier: "Silver" } => "10%",188 _ => "0%"189};190191```text192193### List Patterns (C# 11+)194195```csharp196197bool IsValid(int[] data) => data is [> 0, .., > 0]; // first and last positive198199string Describe(int[] values) => values switch200{201 [] => "empty",202 [var single] => $"single: {single}",203 [var first, .., var last] => $"range: {first}..{last}"204};205206```text207208### Type and Property Patterns209210```csharp211212decimal CalculateShipping(object package) => package switch213{214 Letter { Weight: < 50 } => 0.50m,215 Parcel { Weight: var w } when w < 1000 => 5.00m + w * 0.01m,216 Parcel { IsOversized: true } => 25.00m,217 _ => 10.00m218};219220```text221222---223224## `required` Members (C# 11+)225226Force callers to initialize properties at construction via object initializers.227228```csharp229230public class UserDto231{232 public required string Name { get; init; }233 public required string Email { get; init; }234 public string? Phone { get; init; }235}236237// Compiler enforces Name and Email238var user = new UserDto { Name = "Alice", Email = "alice@example.com" };239240```text241242Useful for DTOs that need to be deserialized (System.Text.Json honors `required` in .NET 8+).243244---245246## `field` Keyword (C# 14, net10.0+)247248Access the compiler-generated backing field directly in property accessors.249250```csharp251252public class TemperatureSensor253{254 public double Reading255 {256 get => field;257 set => field = value >= -273.15258 ? value259 : throw new ArgumentOutOfRangeException(nameof(value));260 }261}262263```text264265Replaces the manual pattern of declaring a private field plus a property with custom logic. Use when you need validation266or transformation in a setter without a separate backing field.267268> **net10.0+ only.** On earlier TFMs, use a traditional private field.269270---271272## Extension Blocks (C# 14, net10.0+)273274Group extension members for a type in a single block.275276```csharp277278public static class EnumerableExtensions279{280 extension<T>(IEnumerable<T> source) where T : class281 {282 public IEnumerable<T> WhereNotNull()283 => source.Where(x => x is not null);284285 public bool IsEmpty()286 => !source.Any();287 }288}289290```text291292> **net10.0+ only.** On earlier TFMs, use traditional `static` extension methods.293294---295296## Alias Any Type (`using`, C# 12+, net8.0+)297298```csharp299300using Point = (double X, double Y);301using UserId = System.Guid;302303Point origin = (0, 0);304UserId id = UserId.NewGuid();305306```text307308Useful for tuple aliases and domain type aliases without creating a full type.309310---311312## `params` Collections (C# 13, net9.0+)313314`params` now supports additional collection types beyond arrays, including `Span<T>`, `ReadOnlySpan<T>`, and types315implementing certain collection interfaces.316317```csharp318319public void Log(params ReadOnlySpan<string> messages)320{321 foreach (var msg in messages)322 Console.WriteLine(msg);323}324325// Callers: compiler may avoid heap allocation with span-based params326Log("hello", "world");327328```text329330> **net9.0+ only.** On net8.0, `params` only supports arrays.331332---333334## `Lock` Type (C# 13, net9.0+)335336Use `System.Threading.Lock` instead of `object` for locking.337338```csharp339340private readonly Lock _lock = new();341342public void DoWork()343{344 lock (_lock)345 {346 // thread-safe operation347 }348}349350```text351352`Lock` provides a `Scope`-based API for advanced scenarios and is more expressive than `lock (object)`.353354> **net9.0+ only.** On net8.0, use `private readonly object _gate = new();` and `lock (_gate)`.355356---357358## Partial Properties (C# 13, net9.0+)359360Partial properties enable source generators to define property signatures that users implement, or vice versa.361362```csharp363364// In generated file365public partial class ViewModel366{367 public partial string Name { get; set; }368}369370// In user file371public partial class ViewModel372{373 private string _name = "";374 public partial string Name375 {376 get => _name;377 set => SetProperty(ref _name, value);378 }379}380381```text382383> **net9.0+ only.** See [skill:dotnet-csharp-source-generators] for generator patterns.384385---386387## `nameof` for Unbound Generic Types (C# 14, net10.0+)388389```csharp390391string name = nameof(List<>); // "List"392string name2 = nameof(Dictionary<,>); // "Dictionary"393394```csharp395396Useful in logging, diagnostics, and reflection scenarios.397398> **net10.0+ only.**399400---401402## Polyfill Guidance for Multi-Targeting403404When targeting multiple TFMs, newer language features may not compile on older targets. Use these approaches:4054061. **PolySharp** -- Polyfills compiler-required types (`IsExternalInit`, `RequiredMemberAttribute`, etc.) so language407 features like `init`, `required`, and `record` work on older TFMs.4082. **Polyfill** -- Polyfills runtime APIs (e.g., `string.Contains(char)` for netstandard2.0).4093. **Conditional compilation** -- Use `#if` for features that cannot be polyfilled:410411```csharp412413#if NET10_0_OR_GREATER414 // Use field keyword415 public double Value { get => field; set => field = Math.Max(0, value); }416#else417 private double _value;418 public double Value { get => _value; set => _value = Math.Max(0, value); }419#endif420421```text422423See [skill:dotnet-multi-targeting] for comprehensive polyfill guidance.424425---426427## Knowledge Sources428429Feature guidance in this skill is grounded in publicly available language design rationale from:430431- **C# Language Design Notes (Mads Torgersen et al.)** -- Design decisions behind each C# version's features. Key432 rationale relevant to this skill: primary constructors (reducing boilerplate for DI-heavy services), collection433 expressions (unifying collection initialization syntax), `field` keyword (eliminating backing field ceremony), and434 extension blocks (grouping extensions by target type). Each feature balances expressiveness with safety -- e.g.,435 primary constructor parameters are intentionally mutable captures (not readonly) to keep the feature simple; use436 explicit readonly fields when immutability is needed. Source: https://github.com/dotnet/csharplang/tree/main/meetings437- **C# Language Proposals Repository** -- Detailed specifications and design rationale for accepted and proposed438 features. Source: https://github.com/dotnet/csharplang/tree/main/proposals439440> **Note:** This skill applies publicly documented design rationale. It does not represent or speak for the named441> sources.442443## References444445- [C# Language Reference](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/)446- [What's new in C# 12](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12)447- [What's new in C# 13](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-13)448- [What's new in C# 14](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-14)449- [C# Language Design Notes](https://github.com/dotnet/csharplang/tree/main/meetings)450- [.NET Framework Design Guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/)451````