Select Page

A production C# code review needs a concrete answer to three questions: what behavior does the caller rely on, which change could break it, and what evidence would catch that break? A checklist becomes useful when each answer points to a contract, a test, or an explicit limit.

This walkthrough reviews a small method that loads integer settings into a dictionary. It catches a silent duplicate-key overwrite and checks the corrected behavior. The complete console program was compiled and run targeting .NET 10 in an isolated Linux SDK container on November 9, 2026, with nullable reference analysis enabled and warnings treated as errors. It uses only the .NET base class library.

Start the review with a caller contract

For this application, setting names ignore case. A null input array is invalid; null, empty, or whitespace-only keys are invalid; duplicate names must fail instead of replacing a value. Empty input is allowed. Nonblank keys retain their spaces, and integer values are copied without range validation. These are application rules to agree on before reviewing the implementation.

The returned dictionary must own its storage: editing the input array later must not change a completed result. The result is still mutable. If these rules do not suit your application, change the contract and its tests together.

Use this checklist while reading the change

Review questions and the evidence required for this loader
Review question Concrete evidence Decision
Is the caller contract explicit? Null collection, blank key, duplicate, empty input, and valid lookup cases. Request tests for any undocumented boundary before approving.
Does key identity match the domain? The dictionary uses an explicit comparer; lookup with WORKERS finds Workers. Require the same comparison rule for duplicate detection and lookup.
Can a write silently discard data? A two-row duplicate input must throw, including a case-only duplicate. Reject the overwrite implementation.
Who owns the mutable data? Change the source after loading, then change the result; each must remain independent. Keep the copy behavior explicit; do not describe the result as immutable.
Would the test detect the likely defect? Run the duplicate assertion against a deliberately broken loader. Require the assertion to fail for that negative control.
Does the evidence cover the deployment risk? This fixture has no files, database, concurrent writers, or reload path. Ask for separate boundary tests when the real change introduces those responsibilities.

StringComparer.OrdinalIgnoreCase supplies ordinal comparison that ignores case. This example deliberately chooses that identity rule for setting names. It does not trim keys: a padded, nonblank key remains distinct from an unpadded key.

Microsoft documents that Dictionary.TryAdd reports an existing key by returning false and leaving its value intact. The dictionary indexer can replace an existing value. Here the loader converts a false result into an argument exception because this application’s contract forbids duplicates.

Run the duplicate test before trusting it

Create a .NET 10 console project, replace its entire Program.cs with the program below, and run it. No test-framework package is required. These are console commands:

dotnet new console --framework net10.0 --name ReviewChecklist
cd ReviewChecklist
dotnet run

BrokenLoad is a negative control with a deliberate defect. Its dictionary assignment replaces the first value when the second equivalent key arrives. The exception assertion therefore fails, and the harness records that failure as evidence that the test detects this defect. The rest of the program checks LoadSettings, the corrected implementation.

using System;
using System.Collections.Generic;

var duplicate = new (string? Key, int Value)[]
{
    ("Workers", 2), ("workers", 8)
};

// Negative control: this loader silently replaces the first setting.
bool defectCaught = false;
try
{
    ExpectThrows<ArgumentException>(() => BrokenLoad(duplicate));
}
catch (InvalidOperationException)
{
    defectCaught = true;
}
Require(defectCaught, "The duplicate test must catch the broken loader.");
Console.WriteLine("PASS: duplicate test catches the broken loader");

var input = new (string? Key, int Value)[]
{
    ("Workers", 2), ("TimeoutSeconds", 30)
};
var result = LoadSettings(input);
Require(result.Count == 2 && result["WORKERS"] == 2,
    "Distinct settings and case-insensitive lookup.");
Require(input[0] == ("Workers", 2), "Input remains unchanged.");
Console.WriteLine("PASS: valid settings and case-insensitive lookup");

ExpectThrows<ArgumentException>(() => LoadSettings(duplicate));
ExpectThrows<ArgumentException>(() => LoadSettings(new[]
{
    (Key: (string?)"Workers", Value: 2), (Key: (string?)"Workers", Value: 8)
}));
Console.WriteLine("PASS: exact and case-only duplicates are rejected");

ExpectThrows<ArgumentNullException>(() => LoadSettings(null));
foreach (string? key in new string?[] { null, "", " \t" })
{
    ExpectThrows<ArgumentException>(() => LoadSettings(new[] { (key, 1) }));
}
Require(LoadSettings(Array.Empty<(string?, int)>()).Count == 0, "Empty input.");
Console.WriteLine("PASS: null, blank and empty input contracts");

var spaced = LoadSettings(new[] { (Key: (string?)" Workers ", Value: 5) });
Require(spaced.ContainsKey(" Workers ") && !spaced.ContainsKey("Workers"),
    "Nonblank keys are preserved without trimming.");
input[0] = ("Workers", 99);
Require(result["Workers"] == 2, "Later input edits do not alter the result.");
result["Workers"] = 7;
Require(input[0].Value == 99, "Result edits do not alter the input.");
Console.WriteLine("PASS: keys are preserved and storage is independent");

static Dictionary<string, int> LoadSettings((string? Key, int Value)[]? entries)
{
    ArgumentNullException.ThrowIfNull(entries);
    var settings = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
    foreach (var (key, value) in entries)
    {
        if (string.IsNullOrWhiteSpace(key))
            throw new ArgumentException("A setting key is required.", nameof(entries));
        if (!settings.TryAdd(key, value))
            throw new ArgumentException("Duplicate setting key.", nameof(entries));
    }
    return settings;
}

static Dictionary<string, int> BrokenLoad((string? Key, int Value)[] entries)
{
    var settings = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
    foreach (var (key, value) in entries)
        settings[key!] = value; // Deliberate defect: duplicate keys overwrite.
    return settings;
}

static void Require(bool condition, string message)
{
    if (!condition) throw new InvalidOperationException(message);
}

static void ExpectThrows<T>(Action action) where T : Exception
{
    try { action(); }
    catch (T) { return; }
    throw new InvalidOperationException($"Expected {typeof(T).Name}.");
}

Expected standard output:

PASS: duplicate test catches the broken loader
PASS: valid settings and case-insensitive lookup
PASS: exact and case-only duplicates are rejected
PASS: null, blank and empty input contracts
PASS: keys are preserved and storage is independent

The first PASS line means the harness detected the deliberate defect; it does not approve the broken implementation. An unexpected exception, missing expected exception, or false condition in the corrected cases escapes the harness and fails the run. ExpectThrows<T> accepts T or a derived exception type; these checks do not assert exact error messages or parameter names.

Turn the result into a review decision

A useful blocking review comment is: “The duplicate Workers/workers input silently replaces the first value. Our contract requires rejection. Please use a checked insertion and keep a regression test for both identical and case-only duplicates.” That comment names the trigger, the consequence, and the acceptance condition.

The storage check answers a different question. The method constructs a new dictionary, and the fixture verifies that later edits to the array and dictionary do not cross that boundary. No shared cache is updated on a failing call. This does not establish transaction safety for a real configuration reload.

All test data is local to this program. There is no clock, randomness, file system, or database dependency, and no disposable resource to clean up. That follows Microsoft’s guidance to make unit tests isolated, repeatable, and self-checking. In a larger suite, give these cases separate names so a failure identifies the broken contract directly.

This run proves the listed in-memory examples, including a known failure case. It does not validate a file parser, a settings schema, Unicode normalization, thread safety, atomic publication of new settings, throughput, or a production deployment. Add evidence for the boundaries your change actually crosses; do not infer those guarantees from five PASS lines.

For the underlying collection syntax, see C# generic collections. For a fuller approach to choosing assertions, continue with tests around observable behavior. If the change shares mutable state across threads, review ConcurrentDictionary compound operations as a separate concern.

Share This