Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

Looking values up by key with a dictionary

An array finds a value by its position. A dictionary finds a value by its key, which is often the more natural question.

Key and value

C#
System.Collections.Generic.Dictionary<string, int> stock =
    new System.Collections.Generic.Dictionary<string, int>();

stock["bolts"] = 120;
stock["nuts"] = 80;

int bolts = stock["bolts"];

What to know before you use one

  • Each key appears once. Assigning an existing key replaces its value.
  • Asking for a key that is not present throws an exception, so check first when the key is uncertain.
  • A dictionary is not ordered in the way a list is, so do not rely on the sequence of its items.
Good fit. Dictionaries suit lookups such as settings by name or a count by product code. For an ordered sequence of items, keep using a list.

Collections are far more useful once you can package behaviour with data, which is the subject of building your own types.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.