Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

C# Tutorial

C# HOME C# Intro C# Get Started C# Syntax C# Output C# Comments C# Variables C# Data Types C# Type Casting C# User Input C# Operators C# Math C# Strings C# Booleans C# If...Else C# Switch C# While Loop C# For Loop C# Break/Continue C# Arrays

C# Methods

C# Methods C# Method Parameters C# Method Overloading C# Scope C# Recursion

C# Classes

C# OOP C# Classes/Objects C# Class Members C# Constructors C# this Keyword C# Access Modifiers C# Properties C# Static C# Inheritance C# Polymorphism C# Abstraction C# Interface C# Enums C# Structs

C# Errors

C# Errors C# Debugging C# Exceptions

C# Data Structures

C# Data Structures C# List C# Dictionary C# HashSet C# Stack C# Queue

C# Advanced

C# Files C# Date and Time C# Nullable Types C# Generics C# Lambda C# LINQ

C# Cert

C# Certificate

C# How To

C# How Tos

C# Examples

C# Examples C# Compiler C# Exercises C# Quiz C# Practice Problems C# Server C# Syllabus C# Study Plan


C# Dictionary


Share

Dictionary

In a List, you find an item by its index: 0, 1, 2 and so on. But sometimes a number is not a good way to find a value.

Think of a phone book. You don't look for "person number 37". You look for a name, and you find the phone number next to it.

A Dictionary works the same way. It stores items in pairs: a key (like the name) and a value (like the phone number). You use the key to find the value.

Like List, Dictionary is in the System.Collections.Generic namespace:

Example

// Include the namespace that holds Dictionary
using System.Collections.Generic;

Create a Dictionary

This example creates a dictionary where each key is a country, and each value is the capital city of that country:

Example

Dictionary<string, string> capitals = new Dictionary<string, string>();
capitals.Add("Norway", "Oslo");
capitals.Add("Japan", "Tokyo");
capitals.Add("Germany", "Berlin");

Console.WriteLine(capitals["Japan"]);  // Tokyo

Try it Yourself »

Example explained

  • In Dictionary<string, string>, the first type is the type of the keys, and the second type is the type of the values. Here, both are strings.
  • Add() adds a key and its value.
  • capitals["Japan"] reads the value of the key "Japan".

Each key can only be in a dictionary once. If you Add() a key that is already there, you get an error.

You can also add the pairs when you create the dictionary. Put each pair inside its own curly braces { }:

Example

Dictionary<string, string> capitals = new Dictionary<string, string>
{
  { "Norway", "Oslo" },
  { "Japan", "Tokyo" },
  { "Germany", "Berlin" }
};

Console.WriteLine(capitals["Norway"]);  // Oslo

Try it Yourself »


Change and Remove Items

The keys and the values can have different types. In this dictionary, the keys are names (string) and the values are ages (int).

To change a value, write the key inside [ ] and give it a new value:

Example

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Liam", 30);
ages.Add("Jenny", 25);

ages["Liam"] = 31;
Console.WriteLine(ages["Liam"]);  // 31

Try it Yourself »

To remove a pair, use Remove() with the key. Count tells you how many pairs the dictionary has:

Example

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Liam", 30);
ages.Add("Jenny", 25);
ages.Add("Angie", 28);

ages.Remove("Jenny");
Console.WriteLine(ages.Count);  // 2

Try it Yourself »



Loop Through a Dictionary

Use a foreach loop to go through all the pairs. Each pair is a KeyValuePair, with a Key and a Value:

Example

Dictionary<string, string> capitals = new Dictionary<string, string>
{
  { "Norway", "Oslo" },
  { "Japan", "Tokyo" },
  { "Germany", "Berlin" }
};

foreach (KeyValuePair<string, string> item in capitals)
{
  Console.WriteLine(item.Key + ": " + item.Value);
}

Try it Yourself »

The types inside KeyValuePair<string, string> are the same as the types of the dictionary.


Check If a Key Exists

If you read a key that does not exist, like capitals["Spain"], the program stops with an error (a KeyNotFoundException).

To avoid this, check the key first with ContainsKey(). It returns true if the key exists, and false if it does not:

Example

Dictionary<string, string> capitals = new Dictionary<string, string>
{
  { "Norway", "Oslo" },
  { "Japan", "Tokyo" },
  { "Germany", "Berlin" }
};

if (capitals.ContainsKey("Spain"))
{
  Console.WriteLine(capitals["Spain"]);
}
else
{
  Console.WriteLine("Spain is not in the dictionary");
}

Try it Yourself »

TryGetValue() checks the key and reads the value in one step. It works like int.TryParse(), which you learned about in ref and out:

  • It returns true if the key exists, and false if not.
  • It puts the value in the out variable.

Example

Dictionary<string, string> capitals = new Dictionary<string, string>
{
  { "Norway", "Oslo" },
  { "Japan", "Tokyo" },
  { "Germany", "Berlin" }
};

if (capitals.TryGetValue("Japan", out string capital))
{
  Console.WriteLine("The capital of Japan is " + capital);
}

Try it Yourself »



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.