C# Dictionary: Add, Update, Loop and Sort with Examples

C# Dictionary tutorial infographic showing Add, TryAdd, indexer updates, case-insensitive key lookup, foreach iteration, LINQ sorting, GetValueOrDefault, grouping, and JSON serialization in .NET 10.

Short answer: A C# dictionary (Dictionary<TKey, TValue>) stores each value under a unique key. Read a value with TryGetValue when the key might be missing, add one without replacing anything with TryAdd, and write dictionary[key] = value only when inserting or replacing is exactly what you want. Choose the key comparer before you add data, because it decides which keys count as duplicates.

Say your store receives the product code CV-100 and needs its price. A dictionary lets you ask for that price directly instead of scanning a list. In this tutorial you'll create a .NET 10 console app in Visual Studio 2026, VS Code, or a terminal, run a complete dictionary program, and then work through the problems that trip up beginners: duplicate keys, letter case, list-to-dictionary conversion, sorting by key or value, JSON, and thread safety. You don't need a database, an API key, or any extra NuGet package.

What Is a C# Dictionary?

A dictionary is a collection of key-value pairs. The key identifies an entry, and the value is the data you store for it. In Dictionary<string, decimal>, every key is a string and every value is a decimal number. The angle-bracket types are generic type arguments. They tell the compiler what the collection accepts, so a wrong type becomes a compile-time error instead of a runtime surprise.

In our catalog, product codes are the keys and prices are the values. CV-100 is not a position, so prices[0] doesn't mean "the first price" in a string-keyed dictionary. Two products can share a price, but two entries can't share a key.

Example product-price entries
Key: product codeValue: price
CV-100$19.99
CV-200$34.50

Figure 1 shows a lookup against this catalog. The comparer makes cv-100 match CV-100, and the returned Boolean tells the program whether a price was found. The prices are sample data, not measurements.

Looking up a product price by dictionary keyThe call TryGetValue with the lowercase key cv-100 reaches a two-column table of sample entries. The comparer ignores letter case, so the first row, key CV-100 with value 19.99, is the match. The second row holds CV-200 with 34.50. The result is found equals true and price equals 19.99m. The table illustrates sample entries, not how a dictionary stores data in memory.Look up the key, receive the valueTryGetValue("cv-100", out price)comparer ignores caseKey (string)Value (decimal)CV-10019.99CV-20034.50found = true, price = 19.99m
Figure 1: The key selects an entry (the highlighted row). The comparer decides which keys match, and the Boolean result tells you whether a value was found.

Before You Start

  • Install the .NET 10 SDK for your operating system. The SDK compiles your code, so a runtime-only install can't build the project. Run dotnet --list-sdks and look for a 10.0. entry. Then use dotnet --version to see which installed SDK the current folder selects.
  • Pick an editor: Visual Studio 2026 with the .NET desktop development workload, Visual Studio Code with the C# Dev Kit extension, or any text editor plus a terminal.
  • Be comfortable with variables, strings, and an if statement. The steps below show how to create and run the project; dictionary-specific syntax is explained as it appears.
  • Remember that everything here is in memory and single-threaded. The data resets on every run, so these programs are learning samples, not a database or a shared cache.

The steps target net10.0 and use the .NET 10 LTS SDK, which the Visual Studio console template lists as .NET 10.0 (Long Term Support). .NET 11 is also a supported release, so you can target net11.0 with the matching SDK instead; the dictionary APIs covered here are available in both. .NET 8 and .NET 9 reached end of support on November 10, 2026, so they aren't recommended for new projects. Check Microsoft's .NET support policy for current dates. The outputs shown below follow each method's documented behavior, so run the programs yourself to confirm them on your machine.

Step 1: Create the Console Project

Choose one of the three options. All of them end with the same empty console project named Codingvila.DictionaryDemo.

Option A: Visual Studio 2026

  1. Start Visual Studio. On the start window, choose Create a new project.
  2. Type console in the search box, set the language filter to C#, and select the Console App template (not the .NET Framework variant). Choose Next.
  3. Enter Codingvila.DictionaryDemo as the project name, keep or change the location, and choose Next.
  4. On the Additional information page, select .NET 10.0 (Long Term Support). Leave Do not use top-level statements unchecked, because every sample in this article is written as top-level statements. Choose Create.
  5. In Solution Explorer, double-click Program.cs. Select all of its contents, delete them, and paste the complete program from Step 2.
  6. Press Ctrl+F5 (Debug > Start Without Debugging). A console window shows the output. Press any key to close it.

If you don't see the .NET project templates, the .NET workload is probably missing. Open the Visual Studio Installer, choose Modify, and tick .NET desktop development. Microsoft's own walkthrough covers the same flow in Create a .NET console application using Visual Studio.

Option B: Visual Studio Code

  1. Install the .NET 10 SDK, Visual Studio Code, and the C# Dev Kit extension. If VS Code asks whether you trust the folder's authors, confirm it for a folder you created yourself.
  2. Create an empty folder for your samples and open it with File > Open Folder.
  3. Open a terminal with Terminal > New Terminal and confirm the SDK version. With the .NET 10 SDK selected, the output starts with 10.. If it starts with 11., a newer installed SDK is selected; this alone is not an error. The project command below still explicitly targets net10.0.
Terminal
dotnet --version
  1. Create the project, move into its folder, and run the template once to prove the setup works. You should see Hello, World!.
Terminal
dotnet new console -n Codingvila.DictionaryDemo -f net10.0
cd Codingvila.DictionaryDemo
dotnet run
  1. Use File > Open Folder again to open the new Codingvila.DictionaryDemo folder, open Program.cs, and replace its contents with the program from Step 2. Save the file.
  2. Run dotnet run in the terminal from the project folder.

Option C: Terminal and any editor

Run the commands from Option B in any terminal, edit Program.cs in the editor you prefer, and run dotnet run from the project folder. Nothing else is required.

Step 2: Run a Complete C# Dictionary Example

Replace the entire contents of Program.cs with the code below. Don't append it after the template's Console.WriteLine("Hello, World!"); line: the sample starts with using directives, which must come before top-level statements. The console template enables implicit usings, so some using lines are optional, but keeping them makes each sample self-explanatory.

C# — complete Program.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

// Product codes are the keys and prices are the values. The comparer makes
// keys case-insensitive, so "cv-100" and "CV-100" are the same key.
var prices = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
{
    ["CV-100"] = 19.99m,
    ["CV-200"] = 34.50m
};

Console.WriteLine($"Initial count: {prices.Count}");

// TryAdd keeps the existing value when the key is already present.
bool added = prices.TryAdd("cv-100", 99.00m);
Console.WriteLine($"Duplicate added: {added}");

// TryGetValue returns false when this key is not present.
if (prices.TryGetValue("cv-100", out decimal price))
{
    Console.WriteLine($"Found CV-100: {Money(price)}");
}

// Assignment inserts a missing key or replaces an existing value.
prices["CV-100"] = 24.50m;
decimal updatedPrice = prices["CV-100"];
Console.WriteLine($"Updated CV-100: {Money(updatedPrice)}");

// A missing key returns false and the default value (0 for decimal).
bool foundBefore = prices.TryGetValue("CV-300", out decimal before);
Console.WriteLine($"Before insert: found={foundBefore}, value={Money(before)}");

// Assignment to a new key inserts it. A stored price of 0 is valid data.
prices["CV-300"] = 0m;
bool foundAfter = prices.TryGetValue("CV-300", out decimal after);
Console.WriteLine($"After insert: found={foundAfter}, value={Money(after)}");

bool removed = prices.Remove("CV-200", out decimal removedPrice);
Console.WriteLine($"Removed CV-200: {removed}, value={Money(removedPrice)}");

// Enumeration order is not a contract, so sort explicitly for display.
foreach (KeyValuePair<string, decimal> pair in
         prices.OrderBy(item => item.Key, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine($"{pair.Key} -> {Money(pair.Value)}");
}

// Format as US dollars regardless of the computer's regional settings.
static string Money(decimal amount) =>
    "$" + amount.ToString("N2", CultureInfo.InvariantCulture);

The program formats prices as US dollars itself, so your computer's regional settings can't change what you see. The m suffix turns a number into a decimal literal. Expected output:

Output
Initial count: 2
Duplicate added: False
Found CV-100: $19.99
Updated CV-100: $24.50
Before insert: found=False, value=$0.00
After insert: found=True, value=$0.00
Removed CV-200: True, value=$34.50
CV-100 -> $24.50
CV-300 -> $0.00

Run the project again whenever you replace Program.cs. Each example starts with fresh in-memory data, so rerunning it restores its initial entries. The later examples are independent replacements for the entire file; do not combine them or put top-level statements in a second source file.

Step 3: Understand Add, Update and Safe Lookup

Create and initialize a dictionary

The constructor creates an empty collection with a case-insensitive ordinal comparer. The index initializer then assigns two entries. Dictionary<string, decimal> accepts string keys and decimal values, so adding an integer key or a string price fails at compile time.

The word var doesn't make a variable dynamically typed. The compiler infers the concrete dictionary type from the constructor. You can replace var with the explicit type Dictionary<string, decimal> and get exactly the same variable.

Add or update a key: choose what happens when it already exists

Choose a write operation by its duplicate-key behavior
OperationMissing keyExisting key
prices.Add(key, value)Adds an entryThrows ArgumentException
prices.TryAdd(key, value)Adds an entry and returns trueKeeps the old value and returns false
prices[key] = valueAdds an entryReplaces the value

In the main program, TryAdd("cv-100", 99.00m) returns false because CV-100 already exists under our comparer, so the original $19.99 stays. The later indexer assignment deliberately changes it to $24.50. Notice that an indexer assignment is not an "update only" operation: an unknown key creates a new entry. A null key throws ArgumentNullException in all three cases.

If a change must apply only to an entry that already exists, check the key first and reject unknown codes. The final example in this tutorial does exactly that. In this single-threaded program the check-then-write sequence is fine, but it isn't atomic on a dictionary shared between threads.

Figure 2 compares the three write operations. Every row starts from the same stored entry, so the rows are alternatives, not sequential steps.

Three outcomes for the same duplicate dictionary keyThree independent cases each start with CV-100 stored at 19.99 and try to write 24.50. Add throws an ArgumentException and the stored value stays 19.99. TryAdd returns false and the stored value stays 19.99. Indexer assignment stores 24.50 and the key count does not change. The values are sample data, not benchmark results.When the key already existsStored: CV-100 = $19.99Incoming: CV-100 = $24.50Adddict.Add(k, v)ArgumentExceptionValue stays $19.99TryAdddict.TryAdd(k, v)Returns falseValue stays $19.99Indexerdict[k] = vStores $24.50Key count unchanged
Figure 2: Each row starts from the same stored entry. Rejecting with an exception, keeping the old value, and replacing it are three different policies, so pick one on purpose.

Check if a key exists and get its value with TryGetValue

The out decimal price argument receives the stored value. The method returns true when the key exists. When it returns false, the output variable holds default(TValue), which is zero for decimal. Always check the Boolean first. In the program, the missing CV-300 and the later stored CV-300 with a price of zero both produce $0.00, and only the Boolean tells them apart.

Use ContainsKey when you only need a yes-or-no answer. When you also need the value, TryGetValue does the job in a single lookup instead of an existence check followed by a second read. Reading prices["UNKNOWN"] directly throws KeyNotFoundException when the key is absent, and it never creates the entry. See Microsoft's reference for TryGetValue.

Remove an entry and inspect the result

The Remove(key, out value) overload returns true and supplies the removed price when the key exists. When it returns false, don't use the output value for anything: treat it as meaningful only after a true result. Microsoft documents both overloads on the Dictionary.Remove reference page.

Count is the number of entries, not the highest key or the allocated capacity. Clear() removes every entry but leaves the dictionary variable in place.

Dictionary Initializers: Two Similar Forms, Different Results

These two initializer forms look alike and behave differently. A collection initializer, written as { key, value }, calls Add. An index initializer, written as [key] = value, uses the indexer, so a repeated key replaces the earlier value. Replace Program.cs with this independent program to see both:

C# — independent initializer example
using System;
using System.Collections.Generic;

try
{
    // Collection initializer: each { key, value } pair calls Add.
    _ = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
    {
        { "CV-100", 19.99m },
        { "cv-100", 24.50m }
    };
}
catch (ArgumentException)
{
    Console.WriteLine("Add initializer: duplicate rejected.");
}

// Index initializer: each [key] = value uses the indexer, so a repeat replaces.
var replace = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
{
    ["CV-100"] = 19.99m,
    ["cv-100"] = 24.50m
};

Console.WriteLine($"Index initializer count: {replace.Count}");
bool replaced = replace["CV-100"] == 24.50m;
Console.WriteLine($"Final value is 24.50: {replaced}");
Output
Add initializer: duplicate rejected.
Index initializer count: 1
Final value is 24.50: True

The catch block exists only to show the exception. Real input-processing code should pick a deliberate validation and recovery policy, such as reporting the duplicate row to the user, rather than swallowing every exception and carrying on silently.

Case-Insensitive Keys, Whitespace and Nulls

The default comparer for string keys is case-sensitive. A comparer supplies the equality and hash-code rules used to locate keys; you cannot replace the dictionary's comparer after construction. StringComparer.OrdinalIgnoreCase compares characters without culture rules, which suits identifiers and codes that your application defines as case-insensitive. It isn't a rule for every dictionary: some external identifiers and case-sensitive protocols require case-sensitive comparison.

A comparer does not trim input. "CV-100" and " CV-100 " are different keys. If surrounding spaces should be ignored, normalize the text the same way when you insert and when you look up, as the final example does with Trim(). Normalizing only one side is a common source of "the key is right there" bugs.

A dictionary key can never be null. Empty and whitespace-only strings are legal keys, so rejecting them is an application rule you have to write yourself. Values are different: if the value type allows null, a successful lookup can return a null value, so don't use a null check as a substitute for the Boolean that TryGetValue returns.

Convert a List or Array to a Dictionary

A value doesn't have to be a number. This independent program indexes Product records by their stock keeping unit (SKU), a product identifier. ToDictionary is a Language Integrated Query (LINQ) method that builds a new dictionary from a sequence. The second conversion adds a duplicate on purpose to show that uniqueness is checked under the comparer you pass:

C# — independent product-index example
using System;
using System.Collections.Generic;
using System.Linq;

Product[] products =
{
    new("CV-100", "Notebook", 19.99m),
    new("CV-200", "Desk mat", 34.50m)
};

Dictionary<string, Product> bySku = products.ToDictionary(
    product => product.Sku,
    product => product,
    StringComparer.OrdinalIgnoreCase);

if (bySku.TryGetValue("cv-100", out Product? found))
{
    Console.WriteLine(found.Name);
}

IEnumerable<Product> withDuplicate =
    products.Append(new Product("cv-100", "Other item", 12m));

try
{
    _ = withDuplicate.ToDictionary(
        product => product.Sku,
        StringComparer.OrdinalIgnoreCase);
}
catch (ArgumentException)
{
    Console.WriteLine("Duplicate SKU rejected during conversion.");
}

public sealed record Product(string Sku, string Name, decimal Price);
Output
Notebook
Duplicate SKU rejected during conversion.

The same pattern works with a List<Product>. ToDictionary throws ArgumentException for duplicate keys and ArgumentNullException for a null key, and it doesn't keep the first or last duplicate for you. The result is a separate dictionary, so later changes to the source list don't appear in it. If several products legitimately share a category, group them or use a lookup instead of pretending the category is a unique key. See the Enumerable.ToDictionary overloads and exception rules.

If your rows come from a DataTable and you need to remove repeated rows before building a dictionary, Codingvila's guide to getting distinct records from a DataTable with LINQ covers that separate step. Removing identical rows does not guarantee unique SKU keys: two different rows can still produce the same key, so keep an explicit duplicate-key policy. Also remember that copying a dictionary of reference-type values does not clone the objects inside it.

Loop, Sort and Search by Value

A foreach loop returns one KeyValuePair<TKey, TValue> per entry, with Key and Value properties. You can also unpack each pair directly with foreach (var (code, price) in prices). The dictionary's Keys and Values properties are read-only views of the same data, not independent lists you can edit.

Enumeration order is not a sorting contract. The main program uses OrderBy(item => item.Key, StringComparer.OrdinalIgnoreCase) to get predictable output. That sorts the sequence you loop over, not the dictionary itself. Use a SortedDictionary<TKey, TValue> when the collection must stay in key order, and expect different costs for lookups and updates.

Sort a dictionary by value

To sort by value, order the pairs by Value and add ThenBy on the key so entries with equal prices always appear in the same order. Here CV-100 and CV-400 share a price on purpose. The sorted result is a new sequence; the dictionary itself is unchanged. This independent program also shows ContainsValue, which searches values linearly and stops if it finds a match. In the worst case it examines every entry, because values are not indexed:

C# — independent sort-by-value example
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

var prices = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
{
    ["CV-100"] = 19.99m,
    ["CV-200"] = 34.50m,
    ["CV-300"] = 9.00m,
    ["CV-400"] = 19.99m
};

// Most expensive first. ThenBy breaks ties so the output is always the same.
foreach (KeyValuePair<string, decimal> pair in prices
             .OrderByDescending(item => item.Value)
             .ThenBy(item => item.Key, StringComparer.OrdinalIgnoreCase))
{
    string text = pair.Value.ToString("N2", CultureInfo.InvariantCulture);
    Console.WriteLine($"{pair.Key}: ${text}");
}

// ContainsValue searches linearly; it can stop at the first match.
Console.WriteLine($"Any item costs 9.00: {prices.ContainsValue(9.00m)}");
Output
CV-200: $34.50
CV-100: $19.99
CV-400: $19.99
CV-300: $9.00
Any item costs 9.00: True

Search by value and change entries while looping

Looking up a key and searching for a value are different jobs. Values can repeat, so there may be zero, one or several matches. To find the codes that cost $24.50, filter the pairs, for example prices.Where(item => item.Value == 24.50m).Select(item => item.Key). That is a scan of every entry, not a reverse key lookup.

Don't add entries while looping over the same dictionary. Microsoft documents that adding an element invalidates the enumerator, and the next MoveNext throws InvalidOperationException. In .NET Core 3.0 and later, Remove and Clear are the documented exceptions that don't invalidate it, but a beginner-friendly loop shouldn't rely on that. Collect the changes first, or loop over a snapshot such as prices.ToArray(). A snapshot protects the loop, not your data from another thread's writes. See the GetEnumerator reference.

Common C# Dictionary Recipes

Four tasks come up again and again once the basics work: returning a default when a key is missing, counting items, storing several values under one key, and finding a key from a value. Replace Program.cs with this independent program, which runs all four:

C# — independent recipes example
using System;
using System.Collections.Generic;
using System.Linq;

// 1. Default value for a missing key
var names = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    ["CV-100"] = "Notebook",
    ["CV-200"] = "Desk mat"
};

string? noFallback = names.GetValueOrDefault("CV-999");
string withFallback = names.GetValueOrDefault("CV-999", "Unknown product");
Console.WriteLine($"Without a fallback the result is null: {noFallback is null}");
Console.WriteLine($"With a fallback: {withFallback}");

// 2. Count how many times each item appears
string[] sold = { "CV-100", "CV-200", "cv-100", "CV-100" };
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

foreach (string soldCode in sold)
{
    counts[soldCode] = counts.GetValueOrDefault(soldCode) + 1;
}

foreach (KeyValuePair<string, int> countEntry in
         counts.OrderBy(entry => entry.Key, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine($"{countEntry.Key} sold {countEntry.Value}");
}

// 3. Store multiple values under one key
(string Category, string Name)[] products =
{
    ("Paper", "Notebook"),
    ("Desk", "Desk mat"),
    ("paper", "Sticky notes")
};

var byCategory = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);

foreach ((string category, string name) in products)
{
    if (!byCategory.TryGetValue(category, out List<string>? productNames))
    {
        productNames = new List<string>();
        byCategory[category] = productNames;
    }

    productNames.Add(name);
}

foreach (KeyValuePair<string, List<string>> groupEntry in
         byCategory.OrderBy(entry => entry.Key, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine($"{groupEntry.Key}: {string.Join(", ", groupEntry.Value)}");
}

// 4. Get the key (or keys) for a value
var prices = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
{
    ["CV-100"] = 19.99m,
    ["CV-200"] = 34.50m,
    ["CV-300"] = 19.99m
};

List<string> samePrice = prices
    .Where(priceEntry => priceEntry.Value == 19.99m)
    .Select(priceEntry => priceEntry.Key)
    .OrderBy(sku => sku, StringComparer.OrdinalIgnoreCase)
    .ToList();

Console.WriteLine($"Price 19.99: {string.Join(", ", samePrice)}");
Output
Without a fallback the result is null: True
With a fallback: Unknown product
CV-100 sold 3
CV-200 sold 1
Desk: Desk mat
Paper: Notebook, Sticky notes
Price 19.99: CV-100, CV-300

Return a default value when a key is missing

GetValueOrDefault reads a value and returns default(TValue) when the key is missing (null for a string), or your own fallback when you provide one. It doesn't throw just because a key is absent, and it never inserts a new entry. Invalid arguments can still throw, such as a null dictionary or, for a regular Dictionary, a null key. For numeric dictionaries, a missing key and a stored zero produce the same result. When that distinction matters, use TryGetValue and check its Boolean return value.

Count how many times each item appears

The line counts[soldCode] = counts.GetValueOrDefault(soldCode) + 1; reads zero for a new key, adds one, and stores the result. That works because indexer assignment inserts a missing key. The comparer treats cv-100 and CV-100 as one key, so the count for CV-100 is 3. This read-then-write pattern isn't safe if several threads update the same dictionary.

Store multiple values under one key

A dictionary key maps to one value, so to keep several, make the value a collection such as List<string>. Look the key up with TryGetValue. If it's missing, create the list, store it, and then add to it. If you only need to group existing data for reading, LINQ's GroupBy or ToLookup can do that without manual list creation.

Get a key from a value

A dictionary is built for key-to-value lookups, so the other direction is a scan with Where and Select. Values can repeat, so the result is a list that may hold zero, one or several keys, and sorting it gives a stable display order. A bare FirstOrDefault returns a default pair when there is no match: the key is null for these string keys, but it is zero for an int key. That default can be mistaken for real data. Returning a list makes both no matches and multiple matches explicit. If you do this often on a large dictionary, maintain a second dictionary in the other direction, and only when its keys are unique.

Serialize a Dictionary to JSON Without Losing Its Rules

A string-keyed dictionary serializes with the built-in System.Text.Json library. JSON carries the data, not the dictionary's custom comparer. Replace Program.cs with this independent program to see the difference:

C# — independent JSON round-trip example
using System;
using System.Collections.Generic;
using System.Text.Json;

var prices = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
{
    ["CV-100"] = 19.99m
};

string json = JsonSerializer.Serialize(prices);
Console.WriteLine(json);

Dictionary<string, decimal> loaded =
    JsonSerializer.Deserialize<Dictionary<string, decimal>>(json)
    ?? throw new JsonException("Expected a JSON object.");

// Deserialization builds a dictionary with the default (case-sensitive) comparer.
bool defaultMatch = loaded.ContainsKey("cv-100");
Console.WriteLine($"Default comparer matches lowercase: {defaultMatch}");

// Pass the comparer again to restore the lookup rule.
var restored = new Dictionary<string, decimal>(
    loaded, StringComparer.OrdinalIgnoreCase);

bool restoredMatch = restored.ContainsKey("cv-100");
Console.WriteLine($"Restored comparer matches lowercase: {restoredMatch}");
Output
{"CV-100":19.99}
Default comparer matches lowercase: False
Restored comparer matches lowercase: True

Use JsonSerializer, not ToString(), when you need JSON. External JSON can contain names that collide under a case-insensitive comparer, and rebuilding the dictionary then throws, so decide how to report those collisions instead of silently dropping a value. Validate sizes and business rules at the input boundary too. Microsoft lists the supported key types in its supported collection types for System.Text.Json.

Put It Together: A Small Product Catalog Class

The earlier programs use a dictionary directly, which is fine for learning. In a real application, wrap it in a small class so every change passes the same checks. This final program normalizes codes, validates prices, reports duplicates with TryAdd, updates only existing entries, and returns a sorted copy instead of exposing the dictionary. Replace Program.cs with it:

C# — complete ProductCatalog example
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

var catalog = new ProductCatalog();

bool addedFirst = catalog.TryAdd("CV-100", 19.99m);
bool addedDuplicate = catalog.TryAdd(" cv-100 ", 99.00m);
bool updated = catalog.TryUpdatePrice("cv-100", 24.50m);
bool updatedMissing = catalog.TryUpdatePrice("CV-999", 10m);

Console.WriteLine($"Add CV-100: {addedFirst}");
Console.WriteLine($"Add duplicate: {addedDuplicate}");
Console.WriteLine($"Update CV-100: {updated}");
Console.WriteLine($"Update CV-999: {updatedMissing}");

catalog.TryAdd("CV-200", 34.50m);

if (catalog.TryGetPrice("CV-100", out decimal price))
{
    Console.WriteLine($"CV-100 costs {Money(price)}");
}

foreach (KeyValuePair<string, decimal> item in catalog.GetSortedSnapshot())
{
    Console.WriteLine($"{item.Key} -> {Money(item.Value)}");
}

try
{
    catalog.TryAdd("   ", 5m);
}
catch (ArgumentException ex)
{
    Console.WriteLine($"Rejected blank code (parameter: {ex.ParamName})");
}

static string Money(decimal amount) =>
    "$" + amount.ToString("N2", CultureInfo.InvariantCulture);

// Types go after the top-level statements.
public sealed class ProductCatalog
{
    // The dictionary is private, so every change goes through the checks below.
    private readonly Dictionary<string, decimal> _prices =
        new(StringComparer.OrdinalIgnoreCase);

    public bool TryAdd(string code, decimal price)
    {
        string key = NormalizeCode(code);
        ValidatePrice(price);
        return _prices.TryAdd(key, price);
    }

    public bool TryUpdatePrice(string code, decimal price)
    {
        string key = NormalizeCode(code);
        ValidatePrice(price);

        if (!_prices.ContainsKey(key))
        {
            return false;
        }

        _prices[key] = price;
        return true;
    }

    public bool TryGetPrice(string code, out decimal price) =>
        _prices.TryGetValue(NormalizeCode(code), out price);

    public IReadOnlyList<KeyValuePair<string, decimal>> GetSortedSnapshot() =>
        _prices.OrderBy(pair => pair.Key, StringComparer.OrdinalIgnoreCase).ToList();

    private static string NormalizeCode(string code)
    {
        if (string.IsNullOrWhiteSpace(code))
        {
            throw new ArgumentException("A product code is required.", nameof(code));
        }

        return code.Trim();
    }

    private static void ValidatePrice(decimal price)
    {
        if (price < 0m)
        {
            throw new ArgumentOutOfRangeException(nameof(price), "Price cannot be negative.");
        }
    }
}

Expected output:

Output
Add CV-100: True
Add duplicate: False
Update CV-100: True
Update CV-999: False
CV-100 costs $24.50
CV-100 -> $24.50
CV-200 -> $34.50
Rejected blank code (parameter: code)

The class keeps the catalog rules together. The dictionary field is private, so callers can't bypass NormalizeCode. The comparer lives in one place, and " cv-100 " is rejected as a duplicate of CV-100 because the code is trimmed first and compared without case. The first spelling you store is the one the dictionary keeps, which is why the output shows CV-100. The returned snapshot is a separate list; its read-only interface is not a promise of deep immutability. This class is not thread-safe. If a writer can overlap readers or other writers, you need a synchronization strategy, as the next section explains.

When a Dictionary Is the Wrong Collection

Choose a collection for the access pattern
NeedStarting pointImportant boundary
Read a value by a unique keyDictionary<TKey, TValue>Choose key equality and duplicate behavior.
Keep a sequence with meaningful positionsList<T>An integer position isn't an identifier key.
Track unique values with no associated dataHashSet<T>No separate value is stored for each key.
Keep entries sorted by keySortedDictionary<TKey, TValue>Different lookup and update costs; sort only if required.
Keep entries in insertion orderOrderedDictionary<TKey, TValue>Available in .NET 9 and later.
Build once, then only readFrozenDictionary<TKey, TValue>Immutable, available in .NET 8 and later; created with ToFrozenDictionary, so it can't be edited afterward.
Share concurrent reads and writesConcurrentDictionary<TKey, TValue>Single operations are safe; a multi-step business rule is still not atomic.

Microsoft's documentation states that the default System.Collections.Generic collections aren't synchronized and that enumerating one isn't thread-safe. Several readers can share a dictionary that nobody is modifying, but putting a mutable dictionary in a singleton doesn't make it safe, and TryAdd on an ordinary dictionary doesn't turn it into a concurrent collection. ConcurrentDictionary gives you thread-safe operations such as GetOrAdd, where the value factory may run more than once under contention. It still provides no persistence, expiration, memory limits or transactions.

Key-based access is documented as close to constant time, but that's not a promise that every lookup takes the same time or that a dictionary always beats a list. Hashing, equality, allocation and key size all matter. Never mutate a key object in a way that changes its hash or equality while it's stored in the dictionary. This guide makes no timing or speedup claim.

Common C# Dictionary Errors and Fixes

If dotnet is not found, install the SDK and reopen your terminal. If net10.0 is unavailable, check dotnet --list-sdks and any global.json in the project or its parent folders. That file can select an older SDK; install the required SDK or deliberately update the project's SDK selection. After changing Program.cs, save it and rerun the project.

Symptoms and corrections
SymptomLikely causeCorrection
KeyNotFoundException: "The given key was not present in the dictionary" (newer runtimes include the key in the message)Indexer read with an absent keyUse TryGetValue, or GetValueOrDefault when a fallback value is fine.
ArgumentException about a duplicate keyAdd, a collection initializer or ToDictionary met an equal keyDecide deliberately between reject, keep, replace or group.
ArgumentNullExceptionA null key was passedValidate key input before the call.
A value is replaced unexpectedlyIndexer assignment or an index initializer reused a keyUse Add or TryAdd when replacement isn't intended.
Lookup fails for different letter case or stray spacesCase-sensitive default comparer, or untrimmed inputPass a comparer at construction and normalize text the same way everywhere.
A missing value looks like zeroThe TryGetValue Boolean was ignoredCheck the Boolean before using the out value.
Displayed order changesCode relied on dictionary enumeration orderSort with OrderBy, or choose a collection with an ordering contract.
InvalidOperationException: Collection was modifiedAn entry was added inside a foreach over the same dictionaryCollect changes first, or loop over a snapshot.
Compiler error CS8803 or CS8802Code was pasted after a type declaration, or a second file also contains top-level statementsKeep statements first and types after them, and keep top-level statements in only one file per project.
A shared dictionary fails under loadUnsynchronized writes or a multi-step raceReview ownership and synchronization, then choose a suitable concurrent design.

Frequently Asked Questions

Can a C# dictionary have duplicate values?

Yes. Different keys can store the same value. Only keys must be unique, and uniqueness is decided by the comparer. A price is therefore a poor reverse key when several products can share it.

Does TryGetValue add a missing key?

No. It only reads and reports success or failure. In the main program, CV-300 doesn't exist until the later indexer assignment inserts it.

Should I use ContainsKey or TryGetValue?

Use ContainsKey when you only need a yes-or-no answer, and TryGetValue when you also need the value. Neither makes a following write atomic on an ordinary shared dictionary.

How do I update a value in a C# dictionary?

Assign through the indexer, as in prices["CV-100"] = 24.50m. That also inserts the key if it's missing. If the entry must already exist, check it first with ContainsKey or TryGetValue, as TryUpdatePrice does in the catalog class.

Is a C# dictionary ordered?

Don't count on it. Enumeration order isn't a documented guarantee, so sort when you display data. If you need insertion order, OrderedDictionary<TKey, TValue> is available in .NET 9 and later, and SortedDictionary<TKey, TValue> keeps entries sorted by key.

How do I get a dictionary item by index?

You don't, because a dictionary is addressed by key, not position. prices[0] looks for a key named 0, and it only compiles when 0 can be converted to the declared key type. It does not compile for this tutorial's string-keyed dictionary. LINQ's ElementAt(0) does return the first enumerated pair, but enumeration order isn't a documented guarantee, so don't use it to mean "first added." If position matters, use a List<T> or OrderedDictionary<TKey, TValue> (.NET 9 and later).

How do I merge two dictionaries?

C# has no built-in merge method for Dictionary<TKey, TValue>, so you loop over the second dictionary and decide what a duplicate key means. Call first.TryAdd(key, value) to keep the existing value, or assign first[key] = value to let the second dictionary win. Avoid Add here unless a duplicate should stop the program with an exception. The first dictionary's comparer decides which keys count as duplicates.

How do I copy a dictionary and keep case-insensitive lookup?

Pass the comparer to the copy constructor, for example new Dictionary<string, decimal>(prices, prices.Comparer). The constructor overloads without a comparer use the default equality comparer, so the copy would silently become case-sensitive. Copying with a comparer that treats more source keys as equal can throw if two formerly distinct keys collide. For object values, the copy still points to the same objects unless you clone them.

Can I use a custom class as a dictionary key?

Yes, if it has correct equality and hashing, and the fields they use stay unchanged while the object is a key. For a simple identifier, an immutable string key is easier to reason about than a mutable object.

Can I use two values as a dictionary key?

Yes. A value tuple such as (string, int) compares its parts, so it works as a composite key, for example a store code plus a product code. Tuples can have named elements, as in (string Store, int Product). Use a record when a reusable named key type would make the code clearer; record equality compares its members. A regular class uses reference identity by default, so two separate instances with the same field values do not automatically match. Use immutable components and define equality and hashing when keys should match by their contents.

Is a dictionary faster than a list?

For finding an item by key in a large collection, a dictionary avoids scanning every element, which is usually why it's recommended. For a handful of items, a list can be just as good, and a list is the right choice when order or position matters. Measure your own workload before optimizing, because this guide makes no timing claim.

What is the difference between Dictionary and Hashtable?

Hashtable is an older non-generic collection that stores keys and values as object. Dictionary<TKey, TValue> is type-safe and is the usual choice in new code.

Conclusion

Start from the lookup your application needs, then define key equality and duplicate behavior. In this C# dictionary example, case-insensitive product codes and decimal prices make those decisions visible: TryGetValue handles a missing code, TryAdd keeps an existing price, and indexer assignment replaces it on purpose.

Keep the console project around as a scratchpad for testing a new assumption before it reaches a larger app. Try missing keys, zero or null values, duplicate input, and different letter case. If your data must be ordered, saved, or shared between writers, choose that behavior explicitly instead of expecting Dictionary<TKey, TValue> to supply it.

About the author

Nikunj Satasiya

Software Engineer

Nikunj Satasiya writes practical tutorials on C#, ASP.NET Core, SQL Server, and Angular at Codingvila. He explains development workflows through focused code examples, clear reasoning, and troubleshooting guidance.

Join the discussion

Ask a question or share an implementation detail. Comments are reviewed before publication.