C# – An item with the same key has already been added

In C# the following exception ‘An item with the same key has already been added’ occurs when duplicate keys are initialized inside a Dictionary. The key is a unique value and same keys cannot exist in a dictionary. The error message already contains enough information to fix this issue.

For Example the below code will give a error because the key 1 is duplicated in the dictionary:

NewDictionary.Add(1,“Name1”);

NewDictionary.Add(1,“Name2”);

The image below shows the exception that occurs due to duplicate keys :

To fix this always make sure that no duplicate keys are present inside a dictionary. The above faulty code will get rid of an exception if the keys are kept unique in a dictionary :

NewDictionary.Add(1,“Name1”);

NewDictionary.Add(2,“Name2”);

Leave a Comment

Your email address will not be published. Required fields are marked *