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()

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

Syntax

using System.Collections.Generic;

// Creates a Dictionary.
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)

// Removes the element with the specified key. Returns true if the element was successfully removed.
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

using System;
using System.Collections.Generic;

// Creates a Dictionary<string, int> and adds elements.
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Tanaka", 85);
scores.Add("Sato", 92);
scores.Add("Suzuki", 78);
Console.WriteLine(scores.Count); // 3

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

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

// Creates a Dictionary with initial values.
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

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 .