C# Dictionary Methods

About This Index
This page is the C# Dictionary Methods index. Each row links to a full guide with syntax, parameters, return value, three examples, and FAQs. All examples use fixed data such as Dictionary<string, int> with names and ages, so the output you see is the output you get.
Learn what a Dictionary is for on /c-sharp/dictionary. Use this page when you need a specific API such as Add(), TryGetValue(), or ContainsKey().
Every key can appear only once. Add throws if you repeat a key, TryAdd returns false, and the indexer d[key] = value overwrites. Also do not depend on the order of pairs when you loop; a Dictionary does not promise one.
How to Call a Dictionary Method
Every Dictionary method is an instance method, so you call it on your dictionary variable:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25); // add a pair
bool added = ages.TryAdd("Ravi", 31); // add if the key is new
bool has = ages.ContainsKey("Asha"); // look up a key
bool found = ages.TryGetValue("Ravi", out int age); // read safely
bool gone = ages.Remove("Asha"); // remove a pair C# Dictionary Methods Table
All method guides in this C# tutorial series (10 tutorials), grouped by purpose.
Add / update
2 methodsPut new key and value pairs into a dictionary. Add throws on a duplicate key, TryAdd returns false instead, and the indexer overwrites.
Look up
3 methodsAsk whether a key or a value exists, and read a value safely without an exception.
| Method | Description | Tutorial |
|---|---|---|
ContainsKey() | Check if a key exists in the Dictionary (true or false). | Try it |
ContainsValue() | Check if any entry has a given value (true or false), by scanning all entries. | Try it |
TryGetValue() | Read a value by key safely, with one lookup and no exception if the key is missing. | Try it |
Remove
2 methodsDelete one pair by key or empty the whole dictionary at once.
Capacity
2 methodsReserve space before a big load, or shrink unused space after a big clean-up.
| Method | Description | Tutorial |
|---|---|---|
EnsureCapacity() | Pre-size the Dictionary so it can hold at least a number of entries without growing. | Try it |
TrimExcess() | Shrink the Dictionary's reserved space to fit its current number of entries. | Try it |
Iteration
1 methodWalk through every key and value pair with foreach or a manual enumerator.
| Method | Description | Tutorial |
|---|---|---|
GetEnumerator() | Get an enumerator that visits every KeyValuePair; foreach calls it for you. | Try it |
Frequently Asked Questions
Start with Add()
Put your first key and value pair into a dictionary. It is the call every beginner needs first.
12 people found this page helpful
