All rules
CA2244Usage Enabled by default: As suggestion

Do not duplicate indexed element initializations

Do not duplicate indexed element initializations

Microsoft docs

Description

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements.

Indexed element initializers in object initializers must initialize unique elements. A duplicate index will overwrite a previous element initialization.

Cause

An object initializer has more than one indexed element initializer with the same constant index. All but the last initializer are redundant.

How to fix violations

To fix violations, remove all the redundant indexed element initializers that are overwritten by any of the subsequent element initializer(s). For example, the following code snippet shows a violation of the rule and couple of potential fixes: A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (period). Choose Remove redundant element initializer from the list of options that's presented. !Code fix for CA2244 - Remove redundant element initializer

Example

using System.Collections.Generic;

class C
{
    public void M()
    {
        var dictionary = new Dictionary<int, int>
        {
            [1] = 1, // CA2244
            [2] = 2,
            [1] = 3
        };
    }
}

When to suppress

Do not suppress violations for this rule.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0