This post will discuss how to add to a Dictionary<TKey,TValue> in C#.

You can add key-value pairs to an existing dictionary using the Dictionary<TKey,TValue>.Add() method. It adds the specified key and value to the dictionary. The following example creates an empty dictionary and invokes the Add() method to add entries.

Download  Run Code

Output:

[A, 1], [B, 2], [C, 3]

 
Note that the Add() method throws an ArgumentException when attempting to add a duplicate key, as shown below:

Download  Run Code

Output:

Unhandled exception. System.ArgumentException: An item with the same key has already been added. Key: A

 
The following version, using the indexer, does not throw an ArgumentException when inserting a duplicate key. It adds a new key-value pair if the key doesn’t already exist in the dictionary. Otherwise, it replaces the value of the specified key if an item with the same key already exists in the dictionary.

Download  Run Code

Output:

[A, 1], [B, 2], [C, 3]

That’s all about adding to a Dictionary<TKey,TValue> in C#.