×

c# · level 2 · unit 1 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A finds a value by its .

A Dictionary stores pairs: a key and the value that goes with it, like a coat check where each ticket fetches one coat. Dictionary<string, int> means the keys are strings and the values are ints. You look things up by key, never by position.

That type is long to type twice, so write instead and C# copies the type from the right. prices["tea"] = 2 adds a pair, or replaces the value if the key is already there. Each key appears only once.

Reading a key that is not there stops the program with KeyNotFoundException. Ask first with : prices.ContainsKey("soup") gives True or False.

using System;
using System.Collections.Generic;

var prices = new Dictionary<string, int>();
prices["tea"] = 2;
prices["cake"] = 3;
prices["tea"] = 3;
Console.WriteLine(prices["tea"]);
Console.WriteLine(prices.Count);
Console.WriteLine(prices.ContainsKey("soup"));

Keys care about capital letters: "Tea" and "tea" are different keys.