Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. dict.Add() / Remove() / Clear()

dict.Add() / Remove() / Clear()

Since: C# 2.0(2005)

The Add(), Remove(), and Clear() methods for Dictionary<TKey, TValue>, which manages key-value pairs.

Syntax

using System.Collections.Generic;

Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();

// Adds a key-value pair. Throws ArgumentException if the key already exists.
dict.Add(TKey key, TValue value)

dict.Remove(TKey key)

// Removes all elements.
dict.Clear()

Method List

MethodDescription
Add(TKey key, TValue value)Adds the specified key-value pair. Throws ArgumentException if the key already exists.
dict[key] = valueSets a value for the key using the indexer. Adds the key if it does not exist; overwrites the value if it does.
Remove(TKey key)Removes the element with the specified key and its associated value. Returns true if the key existed, false otherwise.
Clear()Removes all elements from the Dictionary. Count becomes 0.

Sample Code

Program.cs
using System;
using System.Collections.Generic;

// Creates a Dictionary<string, int> and adds elements.
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Okabe Rintaro", 85);
scores.Add("Makise Kurisu", 92);
scores.Add("Shiina Mayuri", 78);
Console.WriteLine(scores.Count); // 3

// Gets a value using the indexer.
Console.WriteLine(scores["Okabe Rintaro"]); // 85

// Overwrites a value using the indexer (unlike Add(), this does not throw on duplicate keys).
scores["Okabe Rintaro"] = 90;
Console.WriteLine(scores["Okabe Rintaro"]); // 90

Dictionary<string, string> capitals = new Dictionary<string, string>
{
    { "Japan", "Tokyo" },
    { "USA", "Washington D.C." },
    { "France", "Paris" }
};

// Removes an element with Remove().
bool removed = capitals.Remove("France");
Console.WriteLine(removed); // True
Console.WriteLine(capitals.Count); // 2

// Removes all elements with Clear().
scores.Clear();
Console.WriteLine(scores.Count); // 0

Run the following command:

dotnet run
3
85
90
True
2
0

Using the Indexer vs. Add()

Add() throws an exception if the key already exists. When you are unsure whether a key is present, use the indexer dict[key] = value, which adds or overwrites without throwing an exception.

IndexerSample.cs
using System;
using System.Collections.Generic;

Dictionary<string, int> hp = new Dictionary<string, int>
{
    { "Okabe Rintaro", 100 },
    { "Makise Kurisu", 80 }
};

// Overwrite with the indexer (no exception)
hp["Okabe Rintaro"] = 120;
Console.WriteLine(hp["Okabe Rintaro"]); // 120

// Add a new entry with the indexer
hp["Shiina Mayuri"] = 90;
Console.WriteLine(hp.Count); // 3

foreach (var kv in hp)
{
    Console.WriteLine($"{kv.Key}: {kv.Value}");
}

Run the following command:

dotnet run
120
3
Okabe Rintaro: 120
Makise Kurisu: 80
Shiina Mayuri: 90

Common Mistakes

Common Mistake: Calling Add() Twice with the Same Key Throws an Exception

Dictionary keys must be unique. Calling Add() twice with the same key throws an ArgumentException. If duplicates are possible, use the indexer or check in advance with ContainsKey().

using System;
using System.Collections.Generic;

// NG: adding the same key twice with Add()
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Okabe Rintaro", 85);
// scores.Add("Okabe Rintaro", 90); // ArgumentException: An item with the same key has already been added.

The same logic can also be written as:

using System;
using System.Collections.Generic;

// OK: use the indexer to overwrite
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Okabe Rintaro", 85);
scores["Okabe Rintaro"] = 90; // no exception
Console.WriteLine(scores["Okabe Rintaro"]); // 90

Run the following command:

dotnet run
90

Notes

Dictionary keys must be unique. Calling Add() twice with the same key throws an ArgumentException. If you are unsure whether a key already exists, use the indexer dict[key] = value instead, or check in advance with ContainsKey().

Accessing a non-existent key via the indexer throws a KeyNotFoundException. To retrieve a value safely, use TryGetValue().

If you find any errors or copyright issues, please .