Skip to content
Christopher Johnson
Go back

The Twelve Warnings of Christmas

Christmas string lights with an unlit bulb, a replacement bulb, and a screwdriver on a wooden workbench

This article is part of the 2026 C# Advent Calendar

The build passes, but the warnings keep piling up. It’s easy to scroll past the same messages until a missing setting breaks a delivery route or a malformed log call hides the details you need.

You don’t need to clear every warning before making progress. Choose a diagnostic whose consequence you understand, correct the underlying issue, and configure the build to fail when that diagnostic appears again.

If you maintain a C# service, these twelve examples show how to turn selected diagnostics into build checks. Our North Pole Workshop handles gift orders, sleigh routes, and confirmation letters. Each example explains the risk, shows a correction, and identifies its limits. Some address runtime bugs; others preserve useful logs, reduce unnecessary work, or expose maintenance debt.

Reading the examples

These are isolated examples, not a deployed service. Logging examples assume an ILogger supplied by the caller.

The companion repository contains matching Before and After projects and a behavior-check program. Clone it, open the repository’s root directory, and run:

git clone https://github.com/Programazing/The-Twelve-Warnings-of-Christmas.git
cd The-Twelve-Warnings-of-Christmas
dotnet run --project checks/Workshop.Checks --configuration Release

You need the .NET 11 SDK, internet access for package restore, and normal globalization support for en-US and de-DE. Warnings from Before are intentional. A successful run ends with Behavior checks finished. Failures: 0.

The companion was verified locally on Fedora 45 x64 using .NET SDK 11.0.100 and runtime 11.0.0. All twelve behavior-check groups passed, After built without warnings or errors, and four deliberate regressions were rejected with the expected diagnostics. The projects target net11.0 and explicitly select C# 15.

To check the diagnostic rules and deliberate regressions yourself, also install Python 3.9 or later and run:

python3 scripts/verify.py

The script records the environment and results, checks diagnostic IDs, and performs the deliberate regressions in temporary copies without changing your working source.

Nullable analysis must be enabled for the nullable-reference warnings:

<PropertyGroup>
  <Nullable>enable</Nullable>
</PropertyGroup>

These examples assume .NET analyzers are enabled. Some CA rules aren’t build warnings by default, so enable the rule explicitly if your build doesn’t report it. The final section shows the configuration for CA2016; substitute the diagnostic ID you want to enforce.

1. A missing sleigh-route region: CS8602

The workshop needs a region to plan its sleigh routes. This code assumes every environment supplies one:

public static string ReadRegion(IConfiguration configuration)
{
    string? region = configuration["SleighRoute:Region"];

    return region.ToUpperInvariant();
}

With nullable analysis enabled, CS8602 flags the call to ToUpperInvariant(): region might be null. If it is, the call throws NullReferenceException.

Since the region is required, reject a missing value explicitly:

public static string ReadRegion(IConfiguration configuration)
{
    string region = configuration["SleighRoute:Region"]
        ?? throw new InvalidOperationException(
            "Configuration key 'SleighRoute:Region' is missing.");

    return region.ToUpperInvariant();
}

The method still fails if the setting is missing, but now the exception tells you which key to fix.

Adding ! would silence the warning without changing runtime behavior. Substituting an empty string would hide the missing setting. Neither approach enforces the requirement.

This guard rejects null, not blank strings or unknown regions. It runs when the method is called; it doesn’t automatically validate configuration at startup.

2. A gift order without a recipient: CS8618

A gift order needs a recipient and a gift name, but this class lets callers leave both unset:

public class GiftOrder
{
    public string RecipientId { get; init; }
    public string GiftName { get; init; }
    public int Quantity { get; init; }
}

CS8618 flags the two string properties. Declaring them non-nullable doesn’t supply their values. A caller can still write new GiftOrder { Quantity = 1 }, leaving the problem for code that later uses the recipient or gift name.

Make callers supply those values:

public class GiftOrder
{
    public required string RecipientId { get; init; }
    public required string GiftName { get; init; }
    public int Quantity { get; init; }
}

An order initializer now needs both properties:

var order = new GiftOrder
{
    RecipientId = "R-1001",
    GiftName = "Wooden train",
    Quantity = 1
};

For this class, C# object creation must initialize both required properties; omitting either produces CS9035.

required enforces initialization, not valid data. Empty strings satisfy it, and explicitly assigning null produces a separate nullable warning. Checking recipient IDs, gift names, and positive quantities remains a validation concern.

3. A returned gift nobody handled: CS8509

The workshop adds Returned to its gift statuses, but the code that produces delivery labels doesn’t get updated:

public enum GiftStatus
{
    Ordered,
    Wrapped,
    Delivered,
    Returned
}
public static string Describe(GiftStatus status) => status switch
{
    GiftStatus.Ordered => "Waiting for the workshop",
    GiftStatus.Wrapped => "Ready for the sleigh",
    GiftStatus.Delivered => "Delivered"
};

CS8509 flags the missing case. If Returned reaches this switch expression, it throws SwitchExpressionException instead of producing a label.

A catch-all arm such as _ => "Unknown" would remove the warning. A throwing catch-all such as _ => throw new ArgumentOutOfRangeException(nameof(status)) would also satisfy exhaustiveness. Both cover every remaining value, so the compiler won’t flag the next named status you add.

Leaving out the catch-all preserves that reminder, but creates a separate decision. An enum can contain unnamed values such as (GiftStatus)99. Even after handling every named member, the compiler reports CS8524 because those unnamed values remain unhandled.

Handle every named status and suppress only the separate warning about unnamed values:

#pragma warning disable CS8524 // Unnamed values intentionally throw.
public static string Describe(GiftStatus status) => status switch
{
    GiftStatus.Ordered => "Waiting for the workshop",
    GiftStatus.Wrapped => "Ready for the sleigh",
    GiftStatus.Delivered => "Delivered",
    GiftStatus.Returned => "Returned to the workshop"
};
#pragma warning restore CS8524

This is a deliberate tradeoff. Unnamed values still throw, while newly added named members remain visible to CS8509. This reminder works when the switch is recompiled against the updated enum.

The companion verification added GiftStatus.Lost to a temporary copy of After without updating the switch. With CS8509 promoted to an error, compilation failed and identified Lost as unhandled.

Validate externally supplied status values at the boundary. This switch isn’t input validation.

4. A confirmation letter left unfinished: CS4014

The workshop writes a confirmation letter, then records the order in a completion log. This code doesn’t ensure the letter is written first:

public static async Task WriteConfirmationAsync(
    string letterPath,
    string completedLogPath,
    string orderId,
    CancellationToken cancellationToken)
{
    File.WriteAllTextAsync(
        letterPath,
        $"Gift order {orderId} is confirmed.",
        cancellationToken);

    await File.AppendAllLinesAsync(
        completedLogPath,
        [orderId],
        cancellationToken);
}

CS4014 flags the unawaited WriteAllTextAsync call. The method can finish successfully while the letter is still being written, and the completion log can contain an order whose letter write later fails. Awaiting the log operation doesn’t observe the separate task responsible for the letter.

Await the write before recording completion:

await File.WriteAllTextAsync(
    letterPath,
    $"Gift order {orderId} is confirmed.",
    cancellationToken);

await File.AppendAllLinesAsync(
    completedLogPath,
    [orderId],
    cancellationToken);

Now the log operation starts only after the letter write succeeds. If the write faults, await propagates the exception through this method’s returned task so the caller can handle it.

Assigning the task to _ would silence the warning without establishing that ordering or handling its failure. Work that must outlive the caller needs an explicit owner, not a discarded task.

Awaiting both operations doesn’t make them atomic. The letter can be written successfully and the log update still fail. This correction ensures ordering and propagates failures; it doesn’t make the two writes succeed or fail together.

5. Loading sleigh routes after cancellation: CA2016

The caller cancels a route load, but this method never passes that request to the file operation:

public static async Task<string[]> LoadStopsAsync(
    string routeFile,
    CancellationToken cancellationToken)
{
    return await File.ReadAllLinesAsync(routeFile);
}

CA2016 examines methods with a trailing CancellationToken parameter and flags qualifying calls that omit a token they could accept. Accepting a token in the signature doesn’t make the work cancellable on its own.

Forward it:

public static async Task<string[]> LoadStopsAsync(
    string routeFile,
    CancellationToken cancellationToken)
{
    return await File.ReadAllLinesAsync(
        routeFile,
        cancellationToken);
}

The file operation can now observe the caller’s cancellation request. Without that connection, abandoned work can keep using resources after its result is no longer wanted.

The check used an already-cancelled token. Before read the file while After reported cancellation.

Cancellation is cooperative, not an immediate stop or a rollback. The operation might finish before it observes the request. If some work must continue despite cancellation, make that choice explicit and document why.

6. Losing the wrapping failure’s origin: CA2200

A wrapping operation fails, and the workshop logs the exception before passing it back to the caller:

try
{
    ReserveWrappingPaper(quantity);
}
catch (InvalidOperationException ex)
{
    logger.LogError(
        ex,
        "Wrapping failed for gift order {OrderId}",
        orderId);

    throw ex;
}

The logging call isn’t the problem. throw ex; restarts the exception’s stack trace at the rethrow, losing the intervening calls that explain where the failure originated. CA2200 flags that loss.

Use a bare throw inside the catch block:

catch (InvalidOperationException ex)
{
    logger.LogError(
        ex,
        "Wrapping failed for gift order {OrderId}",
        orderId);

    throw;
}

A bare throw preserves the original stack information, helping the caller locate the failure rather than starting the investigation at the rethrow.

Keep the catch only if it serves a purpose, such as recording context unavailable farther up the stack. If all it does is rethrow, remove it. Also consider where the exception is logged. Recording the same failure at every layer can bury useful information in repeated entries.

7. Gift-order logs without named fields: CA2254

This log message contains an order ID, but only as part of the completed string:

logger.LogInformation(
    $"Gift order {orderId} wrapped for {recipientId}");

CA2254 flags the non-constant message template. Interpolation happens before the logging call, so the logger receives text instead of a stable template with separate order and recipient values.

Keep the template constant and pass the values separately:

logger.LogInformation(
    "Gift order {OrderId} wrapped for {RecipientId}",
    orderId,
    recipientId);

The logging system now receives named values alongside the template. A provider that preserves structured properties can expose OrderId and RecipientId as fields for filtering and aggregation.

Whether those fields reach your log store depends on the provider, exporter, and storage configuration. Check an actual stored event before assuming they’re available to query.

8. A missed-sleigh log with missing arguments: CA2017

The workshop records a missed dispatch with three placeholders but only two values:

logger.LogWarning(
    "Gift order {OrderId} for {RecipientId} missed sleigh {SleighId}",
    orderId,
    recipientId);

CA2017 flags the mismatch. The template promises a sleigh ID that the call never supplies.

Pass the missing argument:

logger.LogWarning(
    "Gift order {OrderId} for {RecipientId} missed sleigh {SleighId}",
    orderId,
    recipientId,
    sleighId);

A constant template can still be malformed. In the companion check, a logger that invokes the formatter exposes Before’s missing argument as a FormatException. After produces the complete message.

The same Before call does not throw when passed to NullLogger, which ignores the event without formatting it. Test with a logger that processes the message, not just one that accepts the call.

In these ILogger extension-method calls, arguments bind to placeholders by position. Swapping orderId and recipientId can therefore produce incorrect fields without changing the count. CA2017 catches the mismatch, not the meaning of each value.

9. A nice-list score that depends on server culture: CA1305

The nice-list import uses a period as its decimal separator, with no grouping separators or surrounding whitespace. This parser leaves interpretation to the server’s current culture:

public static decimal ParseScore(string value)
{
    return decimal.Parse(value);
}

CA1305 flags the omission of an explicit format provider.

In the companion check, "98.5" parsed as 985 under de-DE. The input was accepted, but its value changed.

Specify both the culture and the permitted number styles:

public static decimal ParseScore(string value)
{
    return decimal.Parse(
        value,
        NumberStyles.AllowLeadingSign |
        NumberStyles.AllowDecimalPoint,
        CultureInfo.InvariantCulture);
}

InvariantCulture supplies the decimal separator. The styles permit a leading sign and decimal point without enabling grouping separators or surrounding whitespace. Both types belong to System.Globalization.

Passing only InvariantCulture removes culture dependence but still uses NumberStyles.Number, which permits more syntax than this import intends.

The corrected parser returned 98.5 under both en-US and de-DE. The checks also confirmed that it rejects grouping separators and surrounding whitespace.

Parsing is not business validation. A successfully parsed negative score may still be invalid for the nice list. Check the allowed range separately. If rejected records are expected, use TryParse with the same styles and culture, then report which record failed.

10. Rebuilding JSON options for every gift: CA1869

The workshop serializes gift orders using the same settings on every call:

public static string Serialize(GiftOrder order)
{
    var options = new JsonSerializerOptions
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    return JsonSerializer.Serialize(order, options);
}

CA1869 flags a locally created JsonSerializerOptions instance used for a single serialization call. These options also hold serialization metadata caches, so creating them repeatedly can add unnecessary work.

Reuse an instance configured for this operation:

private static readonly JsonSerializerOptions Options = new()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

public static string Serialize(GiftOrder order)
{
    return JsonSerializer.Serialize(order, Options);
}

Configure the instance before its first use. readonly prevents reassignment of the field; it doesn’t make the options object immutable. The serializer makes the instance read-only when it first uses it.

Reusing options avoids repeatedly creating instances for the same configuration and allows their metadata caches to be reused. Whether that produces a meaningful improvement in your service depends on serialization volume and the surrounding work. Measure the application before making claims about CPU savings or request capacity.

11. An aging gift-catalog client: SYSLIB0014

The workshop still downloads its gift catalog with WebClient:

public static string DownloadCatalog(Uri catalogUri)
{
    using var client = new WebClient();

    return client.DownloadString(catalogUri);
}

Constructing WebClient produces SYSLIB0014. Microsoft’s recommended replacement is HttpClient.

Pass an existing client into the method:

public static async Task<string> DownloadCatalogAsync(
    HttpClient httpClient,
    Uri catalogUri,
    CancellationToken cancellationToken)
{
    return await httpClient.GetStringAsync(
        catalogUri,
        cancellationToken);
}

The caller owns the client’s lifetime. This method doesn’t create and dispose a new client for every download.

The change also makes the operation asynchronous and forwards cancellation, so callers need updating. Check authentication, headers, proxy settings, and error handling rather than assuming the replacement behaves the same way.

Obsolete doesn’t mean the call has stopped working or will disappear in the next release. It means you should assess the replacement and plan the work. Runtime APIs can use specific diagnostics such as SYSLIB0014; other obsolete members commonly produce CS0618. Enforce the diagnostic you intend to address.

12. A vulnerable gift-order dependency: NU1903 and NU1904

The Before project deliberately references Newtonsoft.Json 12.0.3:

<ItemGroup>
  <!-- Deliberately vulnerable example. Do not use in production. -->
  <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>

That version is affected by CVE-2024-21907, a high-severity denial-of-service vulnerability involving deeply nested JSON. The first patched version for this advisory is 13.0.1.

NuGet Audit reported NU1903 during the verified restore. NU1903 identifies high-severity findings; NU1904 identifies critical ones. This example demonstrates the high-severity finding, not both warning codes.

After updates the package reference:

<ItemGroup>
  <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

Version 13.0.3 contains the fix for this advisory. That doesn’t establish that it’s the latest release or free of other vulnerabilities. Check current advisories and test the application’s serialization behavior before choosing a version.

After’s effective NuGet Audit policy is:

<PropertyGroup>
  <NuGetAudit>true</NuGetAudit>
  <NuGetAuditMode>all</NuGetAuditMode>
  <WarningsAsErrors>
    $(WarningsAsErrors);NU1900;NU1903;NU1904;NU1905
  </WarningsAsErrors>
</PropertyGroup>

To make a missing vulnerability database an error, explicitly configure the audit source in NuGet.Config. When audit sources are omitted, NuGet falls back to package sources and suppresses NU1905.

The companion explicitly configures nuget.org as its audit source:

<configuration>
  <auditSources>
    <clear />
    <add key="nuget.org"
         value="https://api.nuget.org/v3/index.json" />
  </auditSources>
</configuration>

Setting NuGetAuditMode to all includes direct and transitive dependencies. NU1900 reports problems retrieving or interpreting vulnerability data; NU1905 reports an explicitly configured audit source that does not provide a vulnerability database.

This configuration rejects reported high and critical vulnerabilities, as well as warnings about obtaining advisory data. It still doesn’t prove that every expected project was audited. Check the effective audit configuration and dependencies covered by restore.

The companion verification downgraded a temporary copy of After to 12.0.3. Restore failed with NU1903 as an error, confirming that the high-severity gate was enforced.

New advisory information can make a previously passing restore fail without a source change. Decide who investigates those failures and how exceptions are reviewed. A clean result is meaningful only in the context of the dependencies checked, the available advisory data, and the audit configuration.

Fix one rule, then keep it fixed

Don’t start by making every warning an error. Choose a rule with a consequence you understand and findings small enough to review properly.

Enable it as a warning while investigating. Add this entry to an .editorconfig at the repository root so it applies to the C# files below it:

[*.cs]
dotnet_diagnostic.CA2016.severity = warning

Inspect each finding. Forward the token where cancellation belongs, and document cases where the work must deliberately continue. Don’t accept a bulk fix just because it removes the diagnostics.

After correcting the existing violations, promote that rule:

[*.cs]
dotnet_diagnostic.CA2016.severity = error

Run the build in CI, then temporarily reintroduce a violation to confirm enforcement fails. Remove the deliberate violation before committing. The companion script performs this kind of check in temporary copies so the working source stays unchanged.

Choose the next rule by consequence and review effort, not warning count alone. Ten straightforward findings may be safer to fix than one change that alters cancellation or error-handling behavior.

When an exception is justified, keep it narrow and explain the reason near the code. A suppression should record a decision someone can revisit, not hide a problem nobody wanted to investigate.


Share this post:

Next Post
A Practical Folder Structure for Developers and Solopreneurs