Skip to content

NetFabric/NetFabric.Numerics / .agents/skills/csharp-best-practices

csharp-best-practices

Verified

Modern .NET and C# best practices for code quality, performance, and correctness. USE FOR: choosing struct/class/record/readonly-record-struct; nullable reference types; pattern matching; primary constructors; collection expressions; required members; init-only properties; file-scoped namespaces; global usings; async/await patterns; ConfigureAwait; ValueTask vs Task; CancellationToken propagation; IAsyncEnumerable; Span<T>/Memory<T> usage; avoiding boxing; readonly struct; ArrayPool<T>; FrozenDictionary/FrozenSet; LINQ vs loops in hot paths; ArgumentNullException.ThrowIfNull; ThrowIfNegative; ThrowIfZero; IReadOnlyList return types; error handling patterns; GeneratedRegex; LoggerMessage; source generators for regex and logging; avoiding Math/MathF in favor of static methods on the numeric type. DO NOT USE FOR: generic math interfaces (use dotnet-generic-math); ASP.NET Core middleware; EF Core modeling.

FileKindSize
SKILL.mdskill md4.7 KB
references/async.mdmarkdown3.8 KB
references/language-features.mdmarkdown3.9 KB
references/performance.mdmarkdown4.2 KB
references/source-generators.mdmarkdown3.5 KB

references/source-generators.md

View on GitHub
# Source Generators

## GeneratedRegex (.NET 7+, C# 11+)

Always prefer `[GeneratedRegex]` over `new Regex(...)` or `Regex.IsMatch(...)`.

| `new Regex(...)` | `[GeneratedRegex]` |
|-------------------|--------------------|
| Compiled at runtime | Compiled at build time |
| Allocates on first use | Zero allocation after startup |
| No Roslyn diagnostics | Pattern errors are compile errors |

```csharp
using System.Text.RegularExpressions;

public partial class Validator
{
    // partial method — implementation generated by compiler
    [GeneratedRegex(@"^\d{4}-\d{2}-\d{2}$", RegexOptions.None, matchTimeoutMilliseconds: 1000)]
    private static partial Regex DatePattern();

    public bool IsValidDate(string input) => DatePattern().IsMatch(input);
}
```

Rules:
- The class must be `partial`
- The method must be `static partial` returning `Regex`
- Always set `matchTimeoutMilliseconds` to a positive value (prevents ReDoS)
- Use `RegexOptions.IgnoreCase`, `RegexOptions.Multiline` etc. as flags, not inline `(?i)`

For file-level or top-level usage, put the `partial` method in a `partial class` alongside the consumer, or in a dedicated `static partial class Patterns`.

```csharp
// Dedicated patterns class
internal static partial class Patterns
{
    [GeneratedRegex(@"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b",
        RegexOptions.IgnoreCase, matchTimeoutMilliseconds: 1000)]
    internal static partial Regex Email();

    [GeneratedRegex(@"^\+?[1-9]\d{1,14}$", matchTimeoutMilliseconds: 1000)]
    internal static partial Regex PhoneE164();
}
```

## LoggerMessage (.NET 6+)

Always prefer `[LoggerMessage]` over `_logger.LogInformation(...)` in production code.

| `_logger.LogInformation(...)` | `[LoggerMessage]` |
|-------------------------------|-------------------|
| Allocates `object[]` for params | Zero allocation |
| Evaluates args even when level disabled | Args only evaluated if enabled |
| No event ID enforcement | Event ID explicit |

```csharp
public partial class OrderService(ILogger<OrderService> logger)
{
    // partial method — implementation generated by compiler
    [LoggerMessage(EventId = 1001, Level = LogLevel.Information,
        Message = "Order {OrderId} placed by {UserId}")]
    private partial void LogOrderPlaced(int orderId, string userId);

    [LoggerMessage(EventId = 1002, Level = LogLevel.Warning,
        Message = "Order {OrderId} payment failed: {Reason}")]
    private partial void LogPaymentFailed(int orderId, string reason);

    [LoggerMessage(EventId = 1003, Level = LogLevel.Error,
        Message = "Unhandled error processing order {OrderId}")]
    private partial void LogOrderError(int orderId, Exception ex);

    public async Task PlaceOrderAsync(Order order)
    {
        LogOrderPlaced(order.Id, order.UserId);
        // ...
    }
}
```

Rules:
- The class must be `partial`
- The method must be `partial` (static or instance); use instance to capture `ILogger` via primary ctor
- Assign a unique, stable `EventId` per log message
- Exception parameters must be named `exception` or typed as `Exception` — placed last
- Message template placeholders `{Name}` become structured log properties
- Use `LogLevel.Debug` / `LogLevel.Trace` for high-frequency diagnostics to avoid overhead when disabled

```csharp
// Static variant — pass ILogger explicitly
public static partial class Log
{
    [LoggerMessage(EventId = 2001, Level = LogLevel.Debug,
        Message = "Cache miss for key {Key}")]
    public static partial void CacheMiss(ILogger logger, string key);
}

// Call site
Log.CacheMiss(_logger, cacheKey);
```
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall