C#idiomatic C#
ca2244fundamentals/code-analysis/quality-rules

Code analysis

CA2244: Do not duplicate indexed element initializations

Learn about code analysis rule CA2244: Do not duplicate indexed element initializations

CA2244 Usage enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

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

Rule 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.

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:

csharp
using System.Collections.Generic;

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

class C
{
    public void M()
    {
        var dictionary = new Dictionary<int, int>
        {
            [2] = 2,
            [1] = 3
        };
    }
}
csharp
using System.Collections.Generic;

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

When to suppress warnings

Do not suppress violations for this rule.

See also