Choose composite keys or nested dictionaries in C#

A dictionary does not need a new indexer overload for every possible number of key parts. When a lookup identifies one value by a complete combination, put those parts into a value-based key. When callers frequently retrieve or manage an entire group, nested dictionaries may describe the operation more directly.

Choose the shape from the lookups you need. A two-part identity and two independent indexes are different requirements.

Run both lookup shapes

Use the .NET 10 SDK. Create a console project in a new directory, then replace Program.cs with the example below.

Plain text
dotnet new console --framework net10.0
dotnet run

Run dotnet run after saving the replacement. No additional packages are required.

This example uses an immutable record struct to give the composite identity a name. A tuple such as (string Warehouse, string Product) can also provide value-based equality for a small local lookup. A named key becomes useful when the identity appears in several signatures or needs validation.

C#
using System;
using System.Collections.Generic;

var stock = new Dictionary<StockKey, int>();
var key = new StockKey("north", "BOLT");
stock.Add(key, 12);
Console.WriteLine($"Exact key: {stock[new StockKey("north", "BOLT")]}");
Console.WriteLine($"Different case found: {stock.ContainsKey(new StockKey("NORTH", "BOLT"))}");
Console.WriteLine($"Duplicate inserted: {stock.TryAdd(key, 99)}");
stock[key] = 15;
Console.WriteLine($"Replacement: {stock[key]}");

if (!stock.TryGetValue(new StockKey("south", "BOLT"), out var missing))
	Console.WriteLine("Missing key");

var byWarehouse = new Dictionary<string, Dictionary<string, int>>(StringComparer.OrdinalIgnoreCase) {
	["north"] = new Dictionary<string, int>(StringComparer.Ordinal) { ["BOLT"] = 15 }
};
Console.WriteLine($"Nested lookup: {byWarehouse["NORTH"]["BOLT"]}");

/// <summary>Identifies stock by warehouse and product using value equality.</summary>
public readonly record struct StockKey(string Warehouse, string Product);

Expected output:

Plain text
Exact key: 12
Different case found: False
Duplicate inserted: False
Replacement: 15
Missing key
Nested lookup: 15

The composite key compares both components. The example's default string equality is case-sensitive, which makes north and NORTH different keys. Record-generated equality and tuple equality use their components' equality semantics. Neither automatically makes all contained strings case-insensitive. See record equality and tuple equality .

Define insertion and absence explicitly

Add reports an existing key by throwing ArgumentException. TryAdd returns false and leaves the previous value intact. An indexer assignment replaces an existing value or inserts a new one. Those are three different contracts. Choose one for the operation instead of calling a method “Add” while silently replacing data.

Use TryGetValue when absence is expected. An indexer read throws KeyNotFoundException when the key is absent. The out value alone is insufficient to detect absence because a stored value may equal default, including zero in this example. The Boolean result carries that distinction. These behaviors are specified by Dictionary .

Keep equality stable

Every part that participates in equality and hashing must remain stable while its key is stored. A readonly record struct prevents reassignment of its positional properties, but a reference to a mutable object inside a key can still create a changing identity. Strings work well here because their contents are immutable.

For case-insensitive composite identity, supply an IEqualityComparer<StockKey> that uses the same chosen string comparer in both Equals and GetHashCode. Do not compare without case while hashing with case. Normalizing at input is another option only when the application's identity rules explicitly permit that normalization.

The nested example independently chooses case-insensitive warehouse names and case-sensitive product codes. Both dictionaries need deliberate comparers. Changing only the outer comparer leaves the inner dictionary unchanged.

Choose the access pattern

Use one composite dictionary when most operations know the complete key and need a single value. A partial-key query then requires scanning or another maintained index. Use nesting when operations routinely enumerate, replace or remove everything under one warehouse. Account for empty inner dictionaries after deletion and for the two lookups needed to reach a value.

Neither shape provides transaction semantics for multiple updates, and ordinary dictionaries are not a general solution for concurrent writes. Establish synchronization and consistency requirements separately. Avoid building a family of increasingly wide dictionary subclasses when one explicit key type expresses the same identity.

Source and further reading

This article revisits the problem discussed in the following original answer. The explanation and examples here are newly written for .NET 10.

Dictionary<TKey,TValue> Class (System.Collections.Generic)
Represents a collection of keys and values.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-10.0
Records - C# reference
Learn about the record modifier for class and struct types in C#. Records provide standard support for value based equality on instances of record types.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record
Tuple types - C# reference
C# tuples: lightweight data structures that you can use to group loosely related data elements. Tuples introduce a type that contains multiple public members.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples

Author: Herman Schoenfeld