This post will discuss how to add values to a Dictionary in C#.

1. Using Dictionary<TKey,TValue>.Add(TKey, TValue) method

The Dictionary.Add() method can be used to add the specified key and value to a dictionary. The following method demonstrates how to use the Add method for adding a new key-value pair to an existing dictionary.

Download  Run Code

 
The above code throws an ArgumentException when attempting to add a duplicate key. This can be handled using a try-catch block. The following example demonstrates how to handle the exception if a value with the specified key already exists.

Download  Run Code

2. Using Dictionary<TKey,TValue>.Item[TKey] Property

If you need to update the value for a specific key already present in the Dictionary, you can use the dict[key] = value syntax. This syntax adds the specified key and value to the dictionary if the key does not exist or updates the existing value for the specified key if the key already exists in the dictionary. This is demonstrated below:

Download  Run Code

That’s all about adding values to a Dictionary in C#.