modern-csharp
Skill853 starsChanged yesterdayMITView on GitHub
Modern C# for .NET 10 and C# 14: primary constructors, collection expressions, field keyword, extension members, records, pattern matching, spans, raw string literals. Use for any new C# code, "modern C#", "C# 14", "primary constructor", "collection expression", or modernizing old code. Do NOT use for DI registration (use dependency-injection), error handling (use error-handling), or bulk cleanup (use de-sloppify).
5 other projects use a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- zdanovichnick/dotnet-pilottheir own version, first seen Nov 8, 2026
- codewithmukesh/dotnet-claude-kitword for word, first seen Nov 8, 2026
- snuffish/dotfilestheir own version, first seen Nov 1, 2026
- Resgrid/Coreedited, first seen Oct 8, 2026
- MovGP0/Skillstheir own version, first seen Jun 30, 2026
Other versions5 projects use a version of this.
Word for word · 1
- codewithmukesh/dotnet-claude-kit★ 853100% same
Edited · 1
- Resgrid/Core★ 23985% same
Wrote their own version · 3
- zdanovichnick/dotnet-pilot★ 5same name
- MovGP0/Skills★ 1same name
- snuffish/dotfiles★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository38 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .codex/AGENTS.mdAGENTS.md
- .opencode/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/dotnet-rules.mdCursor rule
- architecture-advisorSkill
- aspireSkill
- authenticationSkill
- build-fixSkill
- cachingSkill
- ci-cdSkill
- code-reviewSkill
- configurationSkill
- console-cliSkill
- dependency-injectionSkill
- desktop-mvvmSkill
- de-sloppifySkill
- dockerSkill
- doctorSkill
- dotnet-initSkill
- ef-coreSkill
- error-handlingSkill
- instinct-systemSkill
- loggingSkill
- messagingSkill
- migrateSkill
- minimal-apiSkill
- modular-slicesSkill
- native-aotSkill
- openapiSkill
- opentelemetrySkill
- resilienceSkill
- scaffoldSkill
- specSkill
- tddSkill
- testingSkill
- verifySkill
- wrap-upSkill
The file
We split this skill into the rules it gives an agent
1 rule. 0 are common, 0 are distinctive, and 1 is very specific to this project.
0
Common
Most of the 3 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 162
Use closed when cases need shared members or state that a union cannot carry.
“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Modern C# (C# 14 / .NET 10)
Core Principles
- Use the newest stable features — C# 14 is the target. Prefer language-level constructs over library workarounds.
- Readability over cleverness — Pattern matching and expression-bodied members improve readability when used appropriately; deeply nested patterns do not.
- Value types where possible — Prefer
record struct,Span<T>, and stack allocation to reduce GC pressure. - Immutability by default — Use
record,readonly,init, andrequiredto make illegal states unrepresentable.
Patterns
Well-Known Features Quick Reference
| Feature | Usage | Example |
| Primary constructors | DI injection, eliminate field assignments | public class OrderService(IOrderRepo repo, TimeProvider clock) { } |
| Collection expressions | [] for all collection types + spread | List<string> names = ["Alice", "Bob"]; / int[] all = [..a, ..b, 99]; |
| Records | DTOs, value objects, immutable data | public record CreateOrderRequest(string CustomerId, List<OrderItem> Items); |
readonly record struct | Small stack-allocated value types | public readonly record struct Money(decimal Amount, string Currency); |
| Pattern matching | Switch expressions, list/property patterns | order switch { { Total: > 1000 } => "Premium", _ => "Standard" }; |
| List patterns | Deconstruct arrays/lists | items switch { [] => "Empty", [var x] => $"One: {x}", [var f, .., var l] => $"{f}..{l}" }; |
Span<T> | Zero-allocation slicing | ReadOnlySpan<char> trimmed = input.Trim(); int.TryParse(trimmed[4..], out id); |
| Raw string literals | Multi-line SQL, JSON, XML | var sql = """ SELECT ... """; / interpolated: $$""" {"id": "{{id}}"} """; |
required members | Enforce initialization | public required string ConnectionString { get; init; } |
is pattern + extraction | Null/type/property check | if (result is { IsSuccess: true, Value: var order }) { ... } |
The field Keyword (C# 14)
Access the auto-generated backing field in property accessors without declaring it manually.
// GOOD — field keyword for validation in auto-property
public class Product
{
public string Name
{
get => field;
set => field = value?.Trim() ?? throw new ArgumentNullException(nameof(value));
}
public decimal Price
{
get => field;
set => field = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value));
}
}Lazy Initialization with field
public class ProductCatalog
{
// Lazy-load on first access — no manual Lazy<T> or backing field
public IReadOnlyList<Product> Products
{
get => field ??= LoadProducts();
}
private static List<Product> LoadProducts() => /* expensive load */;
}Change Notification with field
// INotifyPropertyChanged without manual backing fields
public class OrderViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public string CustomerName
{
get => field;
set
{
if (field == value) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CustomerName)));
}
} = "";
public decimal Total
{
get => field;
set
{
if (field == value) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Total)));
}
}
}Extension Members (C# 14)
C# 14 adds extension blocks inside static classes. Unlike classic extension methods, they support extension properties and static extension members — the receiver is declared once for the whole block.
// GOOD — extension block (shipped C# 14 syntax)
public static class OrderExtensions
{
extension(Order order)
{
public decimal TotalWithTax => order.Total * 1.2m;
public bool IsHighValue => order.Total > 1000m;
public string ToSummary() =>
$"Order #{order.Id}: {order.Total:C} ({order.Items.Count} items)";
}
// Static extension members use the type (no receiver instance)
extension(Order)
{
public static Order Empty => Order.Create("none", [], DateTimeOffset.MinValue);
}
}
// Callers see them as if declared on Order
if (order.IsHighValue) { /* ... */ }Classic this-parameter extension methods still work and coexist — use extension blocks when you need properties or several members on the same receiver.
C# 15 (requires net11.0)
Requires
net11.0/ C# 15. Do not generate these innet10.0projects; they will not compile. C# 14 stays the baseline. Move to net11.0 only when you need unions or runtime async (seeknowledge/dotnet-whats-new.md).
Union types
A union declares a closed set of case types with implicit conversions and exhaustive switch.
// BAD (net11.0) — open hierarchy, switch needs a default arm that hides new cases
public abstract record Pet;
public sealed record Cat(string Name) : Pet;
public sealed record Dog(string Name) : Pet;
string Describe(Pet p) => p switch { Cat c => c.Name, Dog d => d.Name, _ => "?" };
// GOOD (net11.0) — union; compiler checks the switch is exhaustive
public union Pet(Cat, Dog, Bird);
string Describe(Pet p) => p switch { Cat c => c.Name, Dog d => d.Name, Bird b => b.Name };System.Text.Json supports C# unions in .NET 11. For expected failures, prefer a union over exceptions (see the error-handling rules).
closed hierarchies
Use closed when cases need shared members or state that a union cannot carry. Direct descendants are fixed at compile time, so switches need no default arm.
// GOOD (net11.0)
public closed record PaymentResult;
public sealed record Paid(string Receipt) : PaymentResult;
public sealed record Declined(string Reason) : PaymentResult;Extension indexers
// GOOD (net11.0) — indexer in an extension block
public static class QueueExtensions
{
extension<T>(IReadOnlyList<T> list)
{
public T this[Index i] => list[i.GetOffset(list.Count)];
}
}Collection expression arguments
// BAD — must fall back to a constructor to set capacity or comparer
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a", "b" };
// GOOD (net11.0) — arguments go inside the collection expression
HashSet<string> names = [with(StringComparer.OrdinalIgnoreCase), "a", "b"];C# 15 also adds labeled break / continue for leaving an outer loop without flag variables.
Anti-patterns
Don't Use Obsolete Patterns When Modern Alternatives Exist
// BAD — manual backing field when field keyword works
private string _name;
public string Name
{
get => _name;
set => _name = value ?? throw new ArgumentNullException();
}
// BAD — old-style collection initialization
var list = new List<int>() { 1, 2, 3 };
// BAD — Tuple instead of record for domain types
(string Name, decimal Price) product = ("Widget", 9.99m);
// GOOD — record
public record Product(string Name, decimal Price);Don't Over-pattern-match
// BAD — deeply nested pattern that's hard to read
if (order is { Customer: { Address: { Country: { Code: "US" } } } })
// GOOD — extract to a clear method or use sequential checks
if (order.Customer.Address.Country.Code == "US")Don't Use var When the Type Is Not Obvious
// BAD — what type is this?
var result = Process(order);
// GOOD — explicit type when not obvious
Result<Order> result = Process(order);
// Also GOOD — var is fine when type is apparent
var orders = new List<Order>();Decision Guide
| Scenario | Recommendation |
| DTO / API contract | record (reference type) |
| Small value object (2-3 fields) | readonly record struct |
| Service with DI | Primary constructor |
| Collection creation | Collection expression [] |
| Property with validation | field keyword |
| Multi-line string (SQL, JSON) | Raw string literal """ |
| Slicing strings/arrays | Span<T> |
| Type checking + extraction | Pattern matching with is / switch |
| Enforced initialization | required modifier |
| Adding methods to external types | Extension members |
| Closed set of cases (net11.0 only) | C# 15 union or closed hierarchy |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

