C# – Check if key exists in dictionary

When you want to check if a key exists, use Dictionary.ContainsKey(). This returns true if the key exists and otherwise returns false. Here’s an example: This initializes the dictionary with a few items and then checks if one of the key exists. This outputs: Usually you’ll want to do something based on if the key … Read more

System.ArgumentException: An item with the same key has already been added

Problem Dictionaries require keys to be unique. When you try to add a key/value to a dictionary and the key already exists, you get the following exception: System.ArgumentException: An item with the same key has already been added. This can happen when you use Dictionary.Add() or when you initialize a dictionary using the “curly brace” … Read more

C# – Add to a dictionary

The simplest way to add a key/value pair to a dictionary is by using Dictionary.Add(), like this: If the key already exists, Dictionary.Add() throws an ArgumentException because the key must be unique. There are a few other ways to add to a dictionary in different scenarios, which I’ll explain below. Add or update key/value in … Read more