13 AI Coding Rules for C#/.NET Projects

    AI coding assistants can produce C#/.NET code that compiles and runs on a developer's machine but fails in production. This article presents 13 project-level rules that teams can give to AI assistants, enforce in code review, and verify in continuous integration. The rules cover nullable reference types, async code, exception handling, dependency injection, configuration, pagination, logging, resource disposal, and automated quality gates.

    AI coding assistants can quickly generate C#/.NET code that looks correct. The project builds, the endpoints return responses, and the sample data works. Problems often appear only after the code reaches a pre-production environment. Nullable reference warnings get ignored. Async methods hide async void. Thread pool threads get blocked by .Result. Exceptions are swallowed by generic try/catch (Exception) blocks. Data access contexts are held in static fields. Configuration values are scattered through business code as string indexers. These patterns may seem harmless on a developer’s machine. Under high concurrency, long call chains, and error recovery scenarios, they can lead to deadlocks, null reference exceptions, resource leaks, and failures that are hard to diagnose.

    Teams need more than isolated code style suggestions. They need a project-level rule set that an AI assistant can understand, that code reviewers can enforce, and that continuous integration can verify. The 13 rules below target C#/.NET. Each one explains the problem it addresses and how to apply it.

    1. Enable nullable reference types and treat warnings as errors

    Nullable reference types record in the type system whether a value may be null. Without them, an assistant can easily generate string parameters with unclear meaning. Callers assume the value is never null, while downstream code has to add ?. checks at every layer. Eventually the code throws a null reference exception at runtime.

    Enable these settings in new projects and in projects that can be migrated:

    1. <PropertyGroup>
    2. <Nullable>enable</Nullable>
    3. <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    4. <LangVersion>latest</LangVersion>
    5. </PropertyGroup>

    The team should also agree on the convention. Customer? means the value may be null, and Customer means it is never null. Do not use the null-forgiving operator (!) to suppress warnings. Suppressing a warning silences the compiler but does not remove the runtime risk. For boundary input that cannot be proven safe, validate it at the entry point and convert it to a non-nullable type. Do not pass the uncertainty into the business layer.

    2. Prefer record types for DTOs, events, and value equality types

    If a type is essentially data with value equality and immutability, prefer record or record struct. Examples include request and response objects, domain events, paged results, and value objects. AI assistants tend to generate mutable classes and hand-write Equals and GetHashCode. When a new property is added, the equality logic can be missed, which creates hidden defects.

    1. public sealed record OrderSummary(
    2. Guid Id,
    3. Guid CustomerId,
    4. decimal Total,
    5. IReadOnlyList<OrderLine> Lines);

    The with expression creates a new instance without changing the original, which suits cases where a new value is derived from an old one. Entities that have identity and lifecycle behavior should remain class types. Use record types for transfer objects, events, query results, and value objects. The rule should state these boundaries clearly so the assistant does not convert every type to a record mechanically.

    3. Use switch expressions instead of long if/else chains

    Pattern matching is a key C# feature, but generated code often still uses long chains such as if (x is Foo f && f.Bar > 0). These chains are hard to read and can miss branches. A switch expression is more compact, and it lets the compiler check that all cases are covered.

    1. public static decimal CalculateFee(Payment p) => p switch
    2. {
    3. { Method: PaymentMethod.Card, Amount: > 1000m } => p.Amount * 0.015m,
    4. { Method: PaymentMethod.Card } => p.Amount * 0.025m,
    5. { Method: PaymentMethod.BankTransfer } => 0m,
    6. _ => throw new ArgumentOutOfRangeException(nameof(p))
    7. };

    Require a switch expression when branching on a type, property, or enum has more than two or three cases. The default branch should not silently return zero. It should throw a clear exception or move to an observable fallback path. This improves readability and makes generated branching logic easier to review.

    4. Avoid async void and keep the Task chain intact

    async void has almost no valid use outside event handlers. Callers cannot await it, exceptions cannot be caught normally, and tests are hard to assert reliably. AI assistants sometimes use it for fire-and-forget logic, which can lose exceptions or crash the process.

    The rule should require business methods to return Task or ValueTask. Only a very small number of entry points, such as UI event handlers, may use async void, and those must catch and log exceptions internally. Async methods should accept a CancellationToken and pass it down the call chain, so that work stops when a request is cancelled.

    1. public async Task<Order> LoadOrderAsync(Guid id, CancellationToken ct)
    2. {
    3. var order = await _reader.GetAsync(id, ct);
    4. return order ?? throw new KeyNotFoundException($"Order {id} not found.");
    5. }

    5. Do not block async code with .Result or .Wait()

    Blocking on async code synchronously is a common cause of deadlocks and thread pool starvation. Treat .Result, .Wait(), or .GetAwaiter().GetResult() in generated code as a high-risk signal. The rule requires await throughout the call chain. If a boundary truly cannot be async, move the async operation to an outer layer instead of blocking deep inside business logic.

    Code reviews should pay close attention to an async method that synchronously waits on another async method. This pattern may work under low concurrency but can quickly exhaust the thread pool under high concurrency. The rule set should prohibit it and enforce the prohibition with analyzers or custom checks.

    6. Catch specific exceptions instead of swallowing generic ones

    A try/catch (Exception) block with an empty catch, or one that only logs a line, is a common bad pattern in generated code. It swallows cancellation exceptions, programming errors, and resource failures, so the problem surfaces later in a more confusing form. The rule should require the following:

    • Catch only specific exceptions that the code can recover from.
    • Use exception filters to distinguish between states.
    • Log context, but never record sensitive information.
    • Keep rethrowing cancellation exceptions.
    1. try
    2. {
    3. await _client.SendAsync(request, ct);
    4. }
    5. catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.BadGateway)
    6. {
    7. _logger.LogWarning(ex, "Upstream returned bad gateway for {RequestId}", request.Id);
    8. throw new UpstreamUnavailableException(request.Id, ex);
    9. }

    The goal of exception handling is not to stop code from ever failing. The goal is to make failures classifiable, observable, and recoverable.

    7. Respect dependency lifetimes and do not hold data access contexts statically

    Static data access contexts, service locators, and capturing scoped services inside singletons all cause concurrency conflicts, state pollution, or resource leaks. The rule should require the following:

    • Inject dependencies through constructors.
    • Use data access contexts within a request scope.
    • Do not store scoped objects in static fields.
    • Do not resolve services directly from the container in business code.

    To avoid writing constructors, assistants may generate static helper classes or service locator calls. The rule set should prohibit these patterns directly and require reviewers to check that lifetimes match.

    8. Use strongly typed configuration objects instead of string indexers

    When configuration values are accessed through string indexers scattered across business code, the compiler cannot check them, and they cannot be validated in one place. The rule should require the following:

    • Bind configuration to strongly typed options objects.
    • Validate required fields and value ranges at startup.
    • Make business code depend only on the options object, not on the raw configuration dictionary.
    1. public sealed class PaymentOptions
    2. {
    3. public decimal FeeRate { get; init; }
    4. }
    5. public sealed class PaymentService
    6. {
    7. private readonly PaymentOptions _options;
    8. public PaymentService(IOptions<PaymentOptions> options)
    9. {
    10. _options = options.Value;
    11. }
    12. }

    Keep sensitive settings outside the source code. Do not hard-code them in source files or in rule examples.

    9. Use server-side pagination, cap page sizes, and allowlist sort fields

    When an assistant generates an endpoint that returns a customer’s paged orders, common problems include loading all records and paging in memory, leaving page size without an upper limit, and concatenating sort fields directly into queries. The rule should require the following:

    • Perform pagination in the data access layer.
    • Set an upper limit on page size.
    • Map sort fields through an allowlist.
    • Project read-only queries to DTOs.
    • Return the page number, page size, and either the total count or cursor information.

    ```csharp
    public sealed record OrderPageRequest(int Page, int PageSize, string? Sort);
    public sealed record OrderPage(IReadOnlyList Items, int Page, int PageSize, long Total);

    public sealed class OrderQueryService
    {
    private readonly IOrderReader _reader;

    1. public OrderQueryService(IOrderReader reader) => _reader