.NET 10 / C# 14 Design Patterns & Style Guide
Provide high-performance, concise, and idiomatic C# 14 solutions. Target CLI-focused development (Zed/VS Code, dotnet CLI).
Core Principles
| Principle |
Approach |
| Conciseness |
Primary constructors, records, field keyword |
| Thread Safety |
Lazy<T>, ConcurrentDictionary, immutable types |
| No Bloat |
Avoid unnecessary abstract factories |
| Minimal APIs |
Prefer over traditional MVC controllers |
| Modular Monolith |
Prefer over complex microservices |
Output Format
- Context - Brief explanation of why the pattern fits
- Code - Modern C# 14 implementation
- Key Features - Highlight C# 14 features used
Pattern Quick Reference
Singleton (Thread-Safe)
public sealed class ConfigService(IOptions<AppSettings> options)
{
private static readonly Lazy<ConfigService> _instance = new(() =>
new ConfigService(/* resolve from DI */));
public static ConfigService Instance => _instance.Value;
public AppSettings Settings => options.Value;
}
Options Pattern (Preferred for Config)
// appsettings.json binding
public record DatabaseOptions
{
public const string Section = "Database";
public required string ConnectionString { get; init; }
public int MaxRetries { get; init; } = 3;
}
// Registration
builder.Services.Configure<DatabaseOptions>(
builder.Configuration.GetSection(DatabaseOptions.Section));
// Usage with primary constructor
public class UserRepository(IOptions<DatabaseOptions> options)
{
private readonly string _connectionString = options.Value.ConnectionString;
}
Factory Pattern (Modern)
public interface IPaymentProcessor { Task ProcessAsync(decimal amount); }
public class PaymentProcessorFactory(IServiceProvider sp)
{
public IPaymentProcessor Create(string type) => type switch
{
"stripe" => sp.GetRequiredService<StripeProcessor>(),
"paypal" => sp.GetRequiredService<PayPalProcessor>(),
_ => throw new ArgumentException($"Unknown processor: {type}")
};
}
Repository Pattern (Generic)
public interface IRepository<T> where T : class
{
ValueTask<T?> GetByIdAsync(int id, CancellationToken ct = default);
IAsyncEnumerable<T> GetAllAsync(CancellationToken ct = default);
Task AddAsync(T entity, CancellationToken ct = default);
Task UpdateAsync(T entity, CancellationToken ct = default);
Task DeleteAsync(int id, CancellationToken ct = default);
}
public class EfRepository<T>(AppDbContext db) : IRepository<T> where T : class
{
public ValueTask<T?> GetByIdAsync(int id, CancellationToken ct = default)
=> db.Set<T>().FindAsync([id], ct);
public IAsyncEnumerable<T> GetAllAsync(CancellationToken ct = default)
=> db.Set<T>().AsAsyncEnumerable();
public async Task AddAsync(T entity, CancellationToken ct = default)
{
db.Set<T>().Add(entity);
await db.SaveChangesAsync(ct);
}
public async Task UpdateAsync(T entity, CancellationToken ct = default)
{
db.Set<T>().Update(entity);
await db.SaveChangesAsync(ct);
}
public async Task DeleteAsync(int id, CancellationToken ct = default)
{
var entity = await GetByIdAsync(id, ct);
if (entity is not null)
{
db.Set<T>().Remove(entity);
await db.SaveChangesAsync(ct);
}
}
}
CQRS (Simplified)
// Commands
public record CreateOrderCommand(string CustomerId, List<OrderItem> Items);
public interface ICommandHandler<TCommand>
{
Task<Result> HandleAsync(TCommand command, CancellationToken ct = default);
}
// Queries
public record GetOrderQuery(int OrderId);
public interface IQueryHandler<TQuery, TResult>
{
Task<TResult> HandleAsync(TQuery query, CancellationToken ct = default);
}
// Minimal API integration
app.MapPost("/orders", async (
CreateOrderCommand cmd,
ICommandHandler<CreateOrderCommand> handler,
CancellationToken ct) =>
{
var result = await handler.HandleAsync(cmd, ct);
return result.IsSuccess ? Results.Created() : Results.BadRequest(result.Error);
});
Minimal API Patterns
var builder = WebApplication.CreateBuilder(args);
// Service registration
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.Configure<DatabaseOptions>(
builder.Configuration.GetSection(DatabaseOptions.Section));
var app = builder.Build();
// Route groups
var api = app.MapGroup("/api/v1");
var users = api.MapGroup("/users").RequireAuthorization();
users.MapGet("/", async (IUserService svc, CancellationToken ct) =>
await svc.GetAllAsync(ct));
users.MapGet("/{id:int}", async (int id, IUserService svc, CancellationToken ct) =>
await svc.GetByIdAsync(id, ct) is { } user
? Results.Ok(user)
: Results.NotFound());
users.MapPost("/", async (CreateUserRequest req, IUserService svc, CancellationToken ct) =>
{
var user = await svc.CreateAsync(req, ct);
return Results.Created($"/api/v1/users/{user.Id}", user);
});
app.Run();
C# 14 Features to Use
| Feature |
Usage |
| Primary constructors |
DI injection: class Service(IRepo repo) |
field keyword |
Backing field access in properties |
| Records |
DTOs, Commands, Queries, Value Objects |
| Required members |
required string Name { get; init; } |
| Collection expressions |
[1, 2, 3] instead of new[] {1, 2, 3} |
| Pattern matching |
Switch expressions for complex conditionals |
Resources
- Design patterns details: See
references/patterns.md
- Minimal API patterns: See
references/minimal-api.md
1---
2name: csharp-dotnet
3description: |
4 Principal .NET 10 Architect providing high-performance, idiomatic C# 14 solutions.
5
6 Use when user asks about:
7 - .NET design patterns (Singleton, Factory, CQRS, Repository, Options Pattern)
8 - C# coding style and best practices
9 - Architecture decisions (Minimal APIs, Modular Monoliths)
10 - Modern C# implementations with primary constructors, records, field keyword
11
12 Triggers: ".NET", "C#", "design pattern", "architecture", "Minimal API",
13 "primary constructor", "record type", "Options Pattern", "Singleton", "Factory",
14 "CQRS", "Repository pattern", "dependency injection"
15metadata:
16 source: https://skillmd.com/skills/aibot88/csharp-dotnet
17---
18
19# .NET 10 / C# 14 Design Patterns & Style Guide
20
21Provide high-performance, concise, and idiomatic C# 14 solutions. Target CLI-focused development (Zed/VS Code, `dotnet` CLI).
22
23## Core Principles
24
25| Principle | Approach |
26|-----------|----------|
27| Conciseness | Primary constructors, records, `field` keyword |
28| Thread Safety | `Lazy<T>`, `ConcurrentDictionary`, immutable types |
29| No Bloat | Avoid unnecessary abstract factories |
30| Minimal APIs | Prefer over traditional MVC controllers |
31| Modular Monolith | Prefer over complex microservices |
32
33## Output Format
34
351. **Context** - Brief explanation of *why* the pattern fits
362. **Code** - Modern C# 14 implementation
373. **Key Features** - Highlight C# 14 features used
38
39## Pattern Quick Reference
40
41### Singleton (Thread-Safe)
42
43```csharp
44public sealed class ConfigService(IOptions<AppSettings> options)
45{
46 private static readonly Lazy<ConfigService> _instance = new(() =>
47 new ConfigService(/* resolve from DI */));
48
49 public static ConfigService Instance => _instance.Value;
50 public AppSettings Settings => options.Value;
51}
52```
53
54### Options Pattern (Preferred for Config)
55
56```csharp
57// appsettings.json binding
58public record DatabaseOptions
59{
60 public const string Section = "Database";
61 public required string ConnectionString { get; init; }
62 public int MaxRetries { get; init; } = 3;
63}
64
65// Registration
66builder.Services.Configure<DatabaseOptions>(
67 builder.Configuration.GetSection(DatabaseOptions.Section));
68
69// Usage with primary constructor
70public class UserRepository(IOptions<DatabaseOptions> options)
71{
72 private readonly string _connectionString = options.Value.ConnectionString;
73}
74```
75
76### Factory Pattern (Modern)
77
78```csharp
79public interface IPaymentProcessor { Task ProcessAsync(decimal amount); }
80
81public class PaymentProcessorFactory(IServiceProvider sp)
82{
83 public IPaymentProcessor Create(string type) => type switch
84 {
85 "stripe" => sp.GetRequiredService<StripeProcessor>(),
86 "paypal" => sp.GetRequiredService<PayPalProcessor>(),
87 _ => throw new ArgumentException($"Unknown processor: {type}")
88 };
89}
90```
91
92### Repository Pattern (Generic)
93
94```csharp
95public interface IRepository<T> where T : class
96{
97 ValueTask<T?> GetByIdAsync(int id, CancellationToken ct = default);
98 IAsyncEnumerable<T> GetAllAsync(CancellationToken ct = default);
99 Task AddAsync(T entity, CancellationToken ct = default);
100 Task UpdateAsync(T entity, CancellationToken ct = default);
101 Task DeleteAsync(int id, CancellationToken ct = default);
102}
103
104public class EfRepository<T>(AppDbContext db) : IRepository<T> where T : class
105{
106 public ValueTask<T?> GetByIdAsync(int id, CancellationToken ct = default)
107 => db.Set<T>().FindAsync([id], ct);
108
109 public IAsyncEnumerable<T> GetAllAsync(CancellationToken ct = default)
110 => db.Set<T>().AsAsyncEnumerable();
111
112 public async Task AddAsync(T entity, CancellationToken ct = default)
113 {
114 db.Set<T>().Add(entity);
115 await db.SaveChangesAsync(ct);
116 }
117
118 public async Task UpdateAsync(T entity, CancellationToken ct = default)
119 {
120 db.Set<T>().Update(entity);
121 await db.SaveChangesAsync(ct);
122 }
123
124 public async Task DeleteAsync(int id, CancellationToken ct = default)
125 {
126 var entity = await GetByIdAsync(id, ct);
127 if (entity is not null)
128 {
129 db.Set<T>().Remove(entity);
130 await db.SaveChangesAsync(ct);
131 }
132 }
133}
134```
135
136### CQRS (Simplified)
137
138```csharp
139// Commands
140public record CreateOrderCommand(string CustomerId, List<OrderItem> Items);
141public interface ICommandHandler<TCommand>
142{
143 Task<Result> HandleAsync(TCommand command, CancellationToken ct = default);
144}
145
146// Queries
147public record GetOrderQuery(int OrderId);
148public interface IQueryHandler<TQuery, TResult>
149{
150 Task<TResult> HandleAsync(TQuery query, CancellationToken ct = default);
151}
152
153// Minimal API integration
154app.MapPost("/orders", async (
155 CreateOrderCommand cmd,
156 ICommandHandler<CreateOrderCommand> handler,
157 CancellationToken ct) =>
158{
159 var result = await handler.HandleAsync(cmd, ct);
160 return result.IsSuccess ? Results.Created() : Results.BadRequest(result.Error);
161});
162```
163
164## Minimal API Patterns
165
166```csharp
167var builder = WebApplication.CreateBuilder(args);
168
169// Service registration
170builder.Services.AddScoped<IUserService, UserService>();
171builder.Services.Configure<DatabaseOptions>(
172 builder.Configuration.GetSection(DatabaseOptions.Section));
173
174var app = builder.Build();
175
176// Route groups
177var api = app.MapGroup("/api/v1");
178var users = api.MapGroup("/users").RequireAuthorization();
179
180users.MapGet("/", async (IUserService svc, CancellationToken ct) =>
181 await svc.GetAllAsync(ct));
182
183users.MapGet("/{id:int}", async (int id, IUserService svc, CancellationToken ct) =>
184 await svc.GetByIdAsync(id, ct) is { } user
185 ? Results.Ok(user)
186 : Results.NotFound());
187
188users.MapPost("/", async (CreateUserRequest req, IUserService svc, CancellationToken ct) =>
189{
190 var user = await svc.CreateAsync(req, ct);
191 return Results.Created($"/api/v1/users/{user.Id}", user);
192});
193
194app.Run();
195```
196
197## C# 14 Features to Use
198
199| Feature | Usage |
200|---------|-------|
201| Primary constructors | DI injection: `class Service(IRepo repo)` |
202| `field` keyword | Backing field access in properties |
203| Records | DTOs, Commands, Queries, Value Objects |
204| Required members | `required string Name { get; init; }` |
205| Collection expressions | `[1, 2, 3]` instead of `new[] {1, 2, 3}` |
206| Pattern matching | Switch expressions for complex conditionals |
207
208## Resources
209
210- **Design patterns details**: See `references/patterns.md`
211- **Minimal API patterns**: See `references/minimal-api.md`