An object initializer has more than one indexed element initializer with the same constant index. All but the last initializer are redundant.
Rule descriptionObject 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 violationsTo 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:
using System.Collections.Generic;
class C
{
public void M()
{
var dictionary = new Dictionary<int, int>
{
[1] = 1, // CA2244
[2] = 2,
[1] = 3
};
}
}
using System.Collections.Generic;
class C
{
public void M()
{
var dictionary = new Dictionary<int, int>
{
[2] = 2,
[1] = 3
};
}
}
using System.Collections.Generic;
class C
{
public void M()
{
var dictionary = new Dictionary<int, int>
{
[1] = 1,
[2] = 2
};
}
}
Tip
A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press Ctrl+. (period). Choose Remove redundant element initializer from the list of options that's presented.
When to suppress warningsDo not suppress violations for this rule.
See alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4