Code inspection: Duplicate keys in dictionary/set initialization
This inspection detects scenarios where a collection contains duplicate keys in its initialization. This typically occurs in collections such as dictionaries, where duplicate keys are not allowed and will lead to a runtime exception.
In the example below, the dictionary initialization includes duplicate keys, which would cause an error during program execution. JetBrains Rider suggests removing or renaming duplicate keys to avoid this issue.
public void InitializeDictionary()
{
var dict = new Dictionary<int, string>
{
{ 1, "First" },
{ 2, "Second" },
{ 1, "Duplicate" }
};
}
public void InitializeDictionary()
{
var dict = new Dictionary<int, string>
{
{ 1, "First" },
{ 2, "Second" },
{ 3, "Duplicate" } // Updated key to remove duplication
};
}
Last modified: 21 March 2025