Start learning free

LESSON 124 OF 674 · DICTIONARIES

Dictionaries in C#

Lesson

In C#, a Dictionary stores key-value pairs where each key maps to a value. It lives in the System.Collections.Generic namespace.

Dictionary<string, int> scores = new Dictionary<string, int>();
scores["Alice"] = 95;
scores["Bob"] = 87;
scores["Charlie"] = 72;

The type parameters <string, int> specify the key type and value type. Assign through the indexer, dict[key] = value, to add entries:

Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 25;
ages["Bob"] = 30;
Console.WriteLine(ages["Alice"]);  // 25
Console.WriteLine(ages.Count);     // 2

Assignment
Follow the Coding Tutorial and create a Dictionary named scores with three student scores!


Hint
Declare Dictionary<string, int> scores = new Dictionary<string, int>() then assign entries with scores["Alice"] = 95;.

STEP 1 OF 2
    Ctrl + Enter to check