agentleFS
mohammed-shaker-devmohammed-shaker-dev/dotnet-claude-skills/CLAUDE.md

dotnet-claude-skills

CLAUDE.md1 starsChanged 10 months agoMITView on GitHub

A comprehensive guide for Claude Code to work effectively with C# and .NET projects. Maintained with best practices from senior .NET architects with 20+ years of experience.

The file

Show its rules and text

We split this CLAUDE.md into the rules it gives an agent

21 rules. About 0 are common, 11 are distinctive, and 10 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈11

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 10

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    File-scoped namespaces: Always use namespace MyApp.Services.

    line 64
  2. Very specific:

    Use decimal for financial/monetary values

    line 148
  3. Distinctive:

    Prefer strong typing over primitive obsession (create value objects)

    line 149
  4. Very specific:

    Use IEnumerable<T> for read-only sequences

    line 150
  5. Very specific:

    Use IReadOnlyCollection<T> or IReadOnlyList<T> for read-only collections with count

    line 151
  6. Very specific:

    Use ICollection<T> or IList<T> for modifiable collections

    line 152
  7. Very specific:

    Use Dictionary<TKey, TValue> for key-value lookups

    line 153
  8. Very specific:

    Prefer Span<T> and Memory<T> for performance-critical scenarios

    line 154
  9. Distinctive:

    Write tests before or alongside implementation (TDD)

    line 802
  10. Distinctive:

    Use in-memory implementations for external services during development

    line 805
  11. Distinctive:

    Keep methods focused and small (<30 lines)

    line 807
  12. Distinctive:

    Use meaningful names (no abbreviations)

    line 808
  13. Distinctive:

    Use cancellation tokens in async methods

    line 810
  14. Distinctive:

    Never comment out functional code to make tests pass

    line 813
  15. Distinctive:

    Don't commit temporary workarounds without documentation

    line 814
  16. Distinctive:

    Avoid magic numbers; use named constants

    line 815
  17. Very specific:

    Don't use async void except for event handlers

    line 816
  18. Very specific:

    Avoid blocking async code (.Result, .Wait())

    line 817
  19. Very specific:

    Don't catch Exception without re-throwing or logging

    line 818
  20. Distinctive:

    Avoid nested ternary operators

    line 819
  21. Distinctive:

    Don't ignore compiler warnings

    line 820

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md for .NET Development

A comprehensive guide for Claude Code to work effectively with C# and .NET projects.
Maintained with best practices from senior .NET architects with 20+ years of experience.


Quick Reference

CommandPurpose
dotnet buildBuild solution
dotnet testRun all tests
dotnet test --filter "FullyQualifiedName~=TestClassName"Run specific tests
dotnet run --project src/ProjectNameRun specific project
dotnet ef migrations add MigrationName -p src/Infrastructure -s src/WebApiAdd EF Core migration
dotnet ef database update -p src/Infrastructure -s src/WebApiApply migrations
dotnet formatFormat code
dotnet clean && dotnet buildClean rebuild

Development Environment

Prerequisites

  • .NET 9 SDK (or latest LTS)
  • Docker and Docker Compose
  • Visual Studio 2022, VS Code with C# Dev Kit, or JetBrains Rider

Project Setup

# Clone and run
git clone <repo-url>
cd <project>
docker-compose up -d        # Start dependencies (DB, Redis, etc.)
dotnet restore
dotnet build
dotnet test
dotnet run --project src/WebApi

Code Style Guidelines

Naming Conventions

ElementConventionExample
NamespacesMatch directory structureMyApp.Core.Services
Classes/Methods/PropertiesPascalCaseOrderService, ProcessOrder()
Parameters/Local variablescamelCaseorderId, customerName
Private fields_camelCase (underscore prefix)_orderRepository
ConstantsPascalCaseMaxRetryCount
InterfacesPrefix with 'I'IOrderRepository
Async methodsSuffix with 'Async'GetOrderAsync()
EnumsPascalCase singularOrderStatus

Formatting Rules

  • Braces: Allman style (on new lines)
  • Indentation: 4 spaces (not tabs)
  • Max line length: ~120 characters
  • One statement per line
  • One declaration per line
  • File-scoped namespaces: Always use namespace MyApp.Services;

Modern C# Features to Use (C# 12/13)

// ✅ Primary constructors for DI
public sealed class OrderService(
    IOrderRepository repository,
    ILogger<OrderService> logger)
{
    public async Task<Order> GetOrderAsync(Guid id) => 
        await repository.GetByIdAsync(id);
}

// ✅ Collection expressions
List<int> numbers = [1, 2, 3, 4, 5];
int[] array = [.. existingList, newItem];

// ✅ Pattern matching
if (result is { IsSuccess: true, Value: var order })
{
    // Use order
}

// ✅ Records for DTOs and Value Objects
public sealed record CreateOrderCommand(
    Guid CustomerId,
    List<OrderItemDto> Items,
    string? Notes = null);

public sealed record OrderCreatedEvent(
    Guid OrderId,
    DateTime CreatedAt) : IDomainEvent;

// ✅ Raw string literals for JSON/SQL
var json = """
    {
        "name": "value",
        "count": 42
    }
    """;

// ✅ Required members
public class Order
{
    public required Guid Id { get; init; }
    public required string CustomerName { get; init; }
}

// ✅ Expression-bodied members
public string FullName => $"{FirstName} {LastName}";
public override string ToString() => $"Order #{Id}";

// ✅ Null-coalescing and null-conditional
var name = customer?.Name ?? "Unknown";
var count = items?.Count ?? 0;

// ✅ Target-typed new
private readonly List<Order> _orders = new();
Dictionary<string, int> counts = new();

// ✅ Global using statements (in GlobalUsings.cs)
global using Microsoft.Extensions.Logging;
global using System.Collections.Generic;

// ✅ C# 13: New Lock type for better thread synchronization
private readonly Lock _lock = new();
public void ThreadSafeOperation()
{
    lock (_lock)
    {
        // Thread-safe work
    }
}

// ✅ C# 13: params collections (not just arrays)
public void LogMessages(params ReadOnlySpan<string> messages)
{
    foreach (var message in messages)
        _logger.LogInformation(message);
}

Type Usage Guidelines

  • Use decimal for financial/monetary values
  • Prefer strong typing over primitive obsession (create value objects)
  • Use IEnumerable<T> for read-only sequences
  • Use IReadOnlyCollection<T> or IReadOnlyList<T> for read-only collections with count
  • Use ICollection<T> or IList<T> for modifiable collections
  • Use Dictionary<TKey, TValue> for key-value lookups
  • Prefer Span<T> and Memory<T> for performance-critical scenarios

Architecture Patterns

Choose the Right Architecture

ScenarioRecommended Architecture
Simple CRUD APIMinimal API + Repository
Business logic complexityClean Architecture
Large distributed systemMicroservices or Modular Monolith
Different read/write patternsCQRS
Audit trail requiredEvent Sourcing
Real-time featuresSignalR + Message Queue

Clean Architecture Structure (when needed)

src/
├── Domain/           # Entities, Value Objects, Domain Events, Interfaces
├── Application/      # Use Cases, Commands, Queries, DTOs, Validators
├── Infrastructure/   # EF Core, External Services, Messaging
└── WebApi/           # Controllers/Endpoints, Middleware, DI Setup

Common Design Patterns

// Repository Pattern
public interface IRepository<T> where T : Entity
{
    Task<T?> GetByIdAsync(Guid id, CancellationToken ct = default);
    Task<IReadOnlyList<T>> GetAllAsync(CancellationToken ct = default);
    Task AddAsync(T entity, CancellationToken ct = default);
    Task UpdateAsync(T entity, CancellationToken ct = default);
    Task DeleteAsync(T entity, CancellationToken ct = default);
}

// Result Pattern (avoid exceptions for expected failures)
public sealed class Result<T>
{
    public bool IsSuccess { get; }
    public T? Value { get; }
    public Error? Error { get; }
    
    private Result(bool isSuccess, T? value, Error? error)
        => (IsSuccess, Value, Error) = (isSuccess, value, error);
    
    public static Result<T> Success(T value) => new(true, value, null);
    public static Result<T> Failure(Error error) => new(false, default, error);
    
    public TResult Match<TResult>(
        Func<T, TResult> onSuccess,
        Func<Error, TResult> onFailure)
        => IsSuccess ? onSuccess(Value!) : onFailure(Error!);
}

public sealed record Error(string Code, string Message);

// Specification Pattern (for complex queries)
public interface ISpecification<T>
{
    Expression<Func<T, bool>> ToExpression();
}

// CQRS with MediatR
public sealed record GetOrderQuery(Guid OrderId) : IRequest<OrderDto?>;

public sealed class GetOrderQueryHandler(IDbContext db) 
    : IRequestHandler<GetOrderQuery, OrderDto?>
{
    public async Task<OrderDto?> Handle(
        GetOrderQuery request, 
        CancellationToken ct)
    {
        return await db.Orders
            .Where(o => o.Id == request.OrderId)
            .Select(o => new OrderDto(o.Id, o.Total))
            .FirstOrDefaultAsync(ct);
    }
}

Dependency Injection Best Practices

// Use constructor injection for required dependencies
public sealed class OrderService(
    IOrderRepository repository,
    IUnitOfWork unitOfWork,
    ILogger<OrderService> logger)
{
    // Primary constructor makes dependencies clear
}

// Register services in extension methods
public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddApplicationServices(
        this IServiceCollection services)
    {
        services.AddScoped<IOrderService, OrderService>();
        services.AddScoped<IOrderRepository, OrderRepository>();
        
        // MediatR
        services.AddMediatR(cfg => 
            cfg.RegisterServicesFromAssembly(typeof(CreateOrderCommand).Assembly));
        
        // FluentValidation
        services.AddValidatorsFromAssemblyContaining<CreateOrderCommandValidator>();
        
        return services;
    }
}

Error Handling

Exception Strategy

// Use exceptions for exceptional conditions only
// Use Result<T> for expected failure cases

// Custom domain exceptions when needed
public sealed class OrderNotFoundException(Guid orderId) 
    : Exception($"Order with ID {orderId} was not found.")
{
    public Guid OrderId { get; } = orderId;
}

// Guard clauses for validation
public void ProcessOrder(Order order)
{
    ArgumentNullException.ThrowIfNull(order);
    
    if (order.Items.Count == 0)
        throw new InvalidOperationException("Order must have at least one item.");
}

// Global exception handling middleware
public sealed class GlobalExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext context,
        Exception exception,
        CancellationToken ct)
    {
        var problemDetails = exception switch
        {
            OrderNotFoundException ex => new ProblemDetails
            {
                Status = StatusCodes.Status404NotFound,
                Title = "Order not found",
                Detail = ex.Message
            },
            ValidationException ex => new ProblemDetails
            {
                Status = StatusCodes.Status400BadRequest,
                Title = "Validation failed",
                Detail = string.Join(", ", ex.Errors.Select(e => e.ErrorMessage))
            },
            _ => new ProblemDetails
            {
                Status = StatusCodes.Status500InternalServerError,
                Title = "An error occurred"
            }
        };

        context.Response.StatusCode = problemDetails.Status!.Value;
        await context.Response.WriteAsJsonAsync(problemDetails, ct);
        return true;
    }
}

Testing Standards

Test Structure

// Test naming: MethodName_Scenario_ExpectedResult
public sealed class OrderServiceTests
{
    private readonly Mock<IOrderRepository> _repositoryMock = new();
    private readonly OrderService _sut;

    public OrderServiceTests()
    {
        _sut = new OrderService(
            _repositoryMock.Object,
            Mock.Of<ILogger<OrderService>>());
    }

    [Fact]
    public async Task GetOrderAsync_WhenOrderExists_ReturnsOrder()
    {
        // Arrange
        var orderId = Guid.NewGuid();
        var expectedOrder = new Order { Id = orderId };
        _repositoryMock
            .Setup(r => r.GetByIdAsync(orderId, default))
            .ReturnsAsync(expectedOrder);

        // Act
        var result = await _sut.GetOrderAsync(orderId);

        // Assert
        result.Should().NotBeNull();
        result!.Id.Should().Be(orderId);
    }

    [Fact]
    public async Task GetOrderAsync_WhenOrderNotFound_ReturnsNull()
    {
        // Arrange
        var orderId = Guid.NewGuid();
        _repositoryMock
            .Setup(r => r.GetByIdAsync(orderId, default))
            .ReturnsAsync((Order?)null);

        // Act
        var result = await _sut.GetOrderAsync(orderId);

        // Assert
        result.Should().BeNull();
    }
}

Integration Tests with Testcontainers

public sealed class OrderApiTests : IAsyncLifetime
{
    private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
        .WithImage("postgres:16-alpine")
        .Build();

    private WebApplicationFactory<Program> _factory = null!;
    private HttpClient _client = null!;

    public async Task InitializeAsync()
    {
        await _postgres.StartAsync();
        
        _factory = new WebApplicationFactory<Program>()
            .WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(services =>
                {
                    services.RemoveAll<DbContextOptions<AppDbContext>>();
                    services.AddDbContext<AppDbContext>(options =>
                        options.UseNpgsql(_postgres.GetConnectionString()));
                });
            });
        
        _client = _factory.CreateClient();
    }

    public async Task DisposeAsync()
    {
        await _factory.DisposeAsync();
        await _postgres.DisposeAsync();
    }

    [Fact]
    public async Task CreateOrder_WithValidData_ReturnsCreated()
    {
        // Arrange
        var command = new CreateOrderCommand(Guid.NewGuid(), [new("SKU-001", 2)]);

        // Act
        var response = await _client.PostAsJsonAsync("/api/orders", command);

        // Assert
        response.StatusCode.Should().Be(HttpStatusCode.Created);
    }
}

Test Commands

# Run all tests
dotnet test

# Run with coverage
dotnet test --collect:"XPlat Code Coverage"

# Run specific test class
dotnet test --filter "FullyQualifiedName~=OrderServiceTests"

# Run specific test
dotnet test --filter "DisplayName~=WhenOrderExists"

# Run tests in parallel
dotnet test --parallel

# Generate coverage report
dotnet tool install -g dotnet-reportgenerator-globaltool
reportgenerator -reports:./coverage.xml -targetdir:./coveragereport

Minimal API Patterns

// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddApplicationServices();
builder.Services.AddInfrastructureServices(builder.Configuration);

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseExceptionHandler();
app.MapOrderEndpoints();

app.Run();

// OrderEndpoints.cs
public static class OrderEndpoints
{
    public static void MapOrderEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/orders")
            .WithTags("Orders")
            .WithOpenApi();

        group.MapGet("/", GetOrders)
            .WithName("GetOrders")
            .Produces<IEnumerable<OrderDto>>();

        group.MapGet("/{id:guid}", GetOrderById)
            .WithName("GetOrderById")
            .Produces<OrderDto>()
            .ProducesProblem(StatusCodes.Status404NotFound);

        group.MapPost("/", CreateOrder)
            .WithName("CreateOrder")
            .Produces<OrderDto>(StatusCodes.Status201Created)
            .ProducesValidationProblem();
    }

    private static async Task<IResult> GetOrders(
        ISender sender,
        CancellationToken ct)
    {
        var orders = await sender.Send(new GetOrdersQuery(), ct);
        return Results.Ok(orders);
    }

    private static async Task<IResult> GetOrderById(
        Guid id,
        ISender sender,
        CancellationToken ct)
    {
        var order = await sender.Send(new GetOrderQuery(id), ct);
        return order is not null 
            ? Results.Ok(order) 
            : Results.NotFound();
    }

    private static async Task<IResult> CreateOrder(
        CreateOrderCommand command,
        ISender sender,
        CancellationToken ct)
    {
        var result = await sender.Send(command, ct);
        return result.Match(
            order => Results.CreatedAtRoute("GetOrderById", new { id = order.Id }, order),
            error => Results.Problem(error.Message, statusCode: 400));
    }
}

Entity Framework Core Best Practices

// DbContext configuration
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) 
    : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<Customer> Customers => Set<Customer>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
    }
}

// Entity configuration (separate file)
public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasKey(o => o.Id);
        
        builder.Property(o => o.Total)
            .HasPrecision(18, 2);
        
        builder.Property(o => o.Status)
            .HasConversion<string>()
            .HasMaxLength(50);
        
        builder.HasMany(o => o.Items)
            .WithOne()
            .HasForeignKey(i => i.OrderId)
            .OnDelete(DeleteBehavior.Cascade);
        
        builder.HasIndex(o => o.CreatedAt);
    }
}

// Efficient querying
public async Task<IReadOnlyList<OrderDto>> GetOrdersAsync(CancellationToken ct)
{
    return await _context.Orders
        .AsNoTracking()  // Read-only queries
        .Where(o => o.Status == OrderStatus.Active)
        .OrderByDescending(o => o.CreatedAt)
        .Select(o => new OrderDto(o.Id, o.Total, o.Status))  // Project early
        .ToListAsync(ct);
}

// Avoid N+1 queries
public async Task<Order?> GetOrderWithItemsAsync(Guid id, CancellationToken ct)
{
    return await _context.Orders
        .Include(o => o.Items)  // Eager loading
        .FirstOrDefaultAsync(o => o.Id == id, ct);
}

Logging Best Practices

// Use structured logging with LoggerMessage
public static partial class LogMessages
{
    [LoggerMessage(
        EventId = 1001,
        Level = LogLevel.Information,
        Message = "Processing order {OrderId} for customer {CustomerId}")]
    public static partial void ProcessingOrder(
        this ILogger logger, 
        Guid orderId, 
        Guid customerId);

    [LoggerMessage(
        EventId = 1002,
        Level = LogLevel.Warning,
        Message = "Order {OrderId} processing took {ElapsedMs}ms (threshold: {ThresholdMs}ms)")]
    public static partial void SlowOrderProcessing(
        this ILogger logger, 
        Guid orderId, 
        long elapsedMs, 
        long thresholdMs);

    [LoggerMessage(
        EventId = 1003,
        Level = LogLevel.Error,
        Message = "Failed to process order {OrderId}")]
    public static partial void OrderProcessingFailed(
        this ILogger logger, 
        Exception exception, 
        Guid orderId);
}

// Usage
public async Task ProcessOrderAsync(Guid orderId, CancellationToken ct)
{
    _logger.ProcessingOrder(orderId, _customerId);
    
    var sw = Stopwatch.StartNew();
    try
    {
        await _processor.ProcessAsync(orderId, ct);
        
        if (sw.ElapsedMilliseconds > 1000)
            _logger.SlowOrderProcessing(orderId, sw.ElapsedMilliseconds, 1000);
    }
    catch (Exception ex)
    {
        _logger.OrderProcessingFailed(ex, orderId);
        throw;
    }
}

Configuration Management

// appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Database=myapp;Username=user;Password=pass"
  },
  "OrderSettings": {
    "MaxItemsPerOrder": 100,
    "DefaultCurrency": "USD",
    "RetryAttempts": 3
  }
}

// Strongly-typed options
public sealed class OrderSettings
{
    public const string SectionName = "OrderSettings";
    
    public int MaxItemsPerOrder { get; init; } = 50;
    public string DefaultCurrency { get; init; } = "USD";
    public int RetryAttempts { get; init; } = 3;
}

// Registration with validation
services.AddOptions<OrderSettings>()
    .BindConfiguration(OrderSettings.SectionName)
    .ValidateDataAnnotations()
    .ValidateOnStart();

// Usage
public sealed class OrderService(IOptions<OrderSettings> options)
{
    private readonly OrderSettings _settings = options.Value;
    
    public void ValidateOrder(Order order)
    {
        if (order.Items.Count > _settings.MaxItemsPerOrder)
            throw new ValidationException(
                $"Order cannot have more than {_settings.MaxItemsPerOrder} items.");
    }
}

Common NuGet Packages

Core Development

<!-- Minimal APIs & Web -->
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.*" />
<PackageReference Include="Serilog.AspNetCore" Version="8.*" />

<!-- Data Access -->
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.*" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.*" />
<PackageReference Include="Dapper" Version="2.*" />

<!-- CQRS & Validation -->
<PackageReference Include="MediatR" Version="12.*" />
<PackageReference Include="FluentValidation" Version="11.*" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.*" />

<!-- Error Handling -->
<PackageReference Include="ErrorOr" Version="2.*" />

<!-- Testing -->
<PackageReference Include="xunit" Version="2.*" />
<PackageReference Include="FluentAssertions" Version="7.*" />
<PackageReference Include="Moq" Version="4.*" />
<PackageReference Include="Testcontainers" Version="4.*" />
<PackageReference Include="Testcontainers.PostgreSql" Version="4.*" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.*" />

<!-- Resilience -->
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.*" />
<PackageReference Include="Polly" Version="8.*" />

Microservices & Messaging

<PackageReference Include="MassTransit" Version="8.*" />
<PackageReference Include="MassTransit.RabbitMQ" Version="8.*" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.*" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.*" />

AI & ML Projects

<!-- Microsoft Agent Framework -->
<PackageReference Include="Microsoft.Agents.AI" Version="1.*-*" />
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.*-*" />

<!-- Azure AI -->
<PackageReference Include="Azure.AI.Projects" Version="1.*" />
<PackageReference Include="Azure.AI.OpenAI" Version="2.*" />
<PackageReference Include="Azure.Identity" Version="1.*" />

<!-- Semantic Kernel -->
<PackageReference Include="Microsoft.SemanticKernel" Version="1.*" />

Documentation Standards

/// <summary>
/// Processes an order and calculates the total amount.
/// </summary>
/// <param name="order">The order to process.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The processed order with calculated totals.</returns>
/// <exception cref="ArgumentNullException">Thrown when order is null.</exception>
/// <exception cref="InvalidOperationException">Thrown when order has no items.</exception>
/// <example>
/// <code>
/// var result = await service.ProcessOrderAsync(order, cancellationToken);
/// if (result.IsSuccess)
/// {
///     Console.WriteLine($"Total: {result.Value.Total}");
/// }
/// </code>
/// </example>
public async Task<Result<Order>> ProcessOrderAsync(
    Order order,
    CancellationToken ct = default)
{
    // Implementation
}

Development Best Practices

Do's ✅

  • Make small, incremental changes
  • Write tests before or alongside implementation (TDD)
  • Implement one feature at a time with proper testing
  • Fix one issue at a time
  • Use in-memory implementations for external services during development
  • Document architecture decisions
  • Keep methods focused and small (<30 lines)
  • Use meaningful names (no abbreviations)
  • Validate method inputs with guard clauses
  • Use cancellation tokens in async methods

Don'ts ❌

  • Never comment out functional code to make tests pass
  • Don't commit temporary workarounds without documentation
  • Avoid magic numbers; use named constants
  • Don't use async void except for event handlers
  • Avoid blocking async code (.Result, .Wait())
  • Don't catch Exception without re-throwing or logging
  • Avoid nested ternary operators
  • Don't ignore compiler warnings

Claude Code Efficiency Tips

Targeted Searches

# GOOD: Specific search
GrepTool pattern="IOrderRepository" include="*.cs"

# BAD: Too broad
GrepTool pattern="Order"

Efficient File Reading

# GOOD: Read specific section of large file
View file_path="/src/Services/OrderService.cs" offset=50 limit=30

# BAD: Read entire large file
View file_path="/src/Services/OrderService.cs"

Batch Operations

# GOOD: Batch multiple operations
BatchTool with multiple View operations for related files

# BAD: Sequential View for each file

Complex Searches

# Use dispatch_agent for cross-file analysis
dispatch_agent prompt="Find all implementations of IRepository interface"

Project Templates

Minimal API Starter

dotnet new webapi -n MyApi --use-minimal-apis
cd MyApi
dotnet add package Serilog.AspNetCore
dotnet add package Swashbuckle.AspNetCore

Clean Architecture Starter

dotnet new sln -n MySolution
dotnet new classlib -n Domain -o src/Domain
dotnet new classlib -n Application -o src/Application
dotnet new classlib -n Infrastructure -o src/Infrastructure
dotnet new webapi -n WebApi -o src/WebApi --use-minimal-apis
dotnet new xunit -n Domain.Tests -o tests/Domain.Tests
dotnet new xunit -n Application.Tests -o tests/Application.Tests
dotnet new xunit -n Integration.Tests -o tests/Integration.Tests

# Add to solution
dotnet sln add src/Domain src/Application src/Infrastructure src/WebApi
dotnet sln add tests/Domain.Tests tests/Application.Tests tests/Integration.Tests

# Add references
dotnet add src/Application reference src/Domain
dotnet add src/Infrastructure reference src/Application
dotnet add src/WebApi reference src/Infrastructure

Additional Resources


Last updated: January 2025 | .NET 9 / C# 13

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.