C#

C#

Made by DeepSource

Dictionary<T, K> has duplicate key(s) in its initializer CS-W1054

Bug risk
Critical

Brace initializer allows you to initialize an element in-place. In case of Dictionary<T, K>, the initializer lets you populate it with keys and values of your choice. In case a key is mentioned more than once, only the last value is preserved and the previous values are evicted. Either you've made a mistake and mapped a key more than once or you meant to specify a different key.

Bad Practice

var dict = new Dictionary<int, int>
{
    [1] = 1,
    [2] = 2,
    [1] = 3, // `1` is mapped again, now maps to `3`.
}

Recommended

var dict = new Dictionary<int, int>
{
    [1] = 1,
    [2] = 2,
    [3] = 3, // Fixed
}

Reference