Overview
This rule flags places where a collection expression with a spread element (..) could be used to initialize a list instead of new. For example, this rule offers to simplify code like new List<...>(x) into the collection expression form ([.. x]).
Options
Options specify the behavior that you want the rule to enforce. For information about configuring options, see Option format.
ms.topic: include
dotnet_style_prefer_collection_expression
| Property | Value | Description |
|---|---|---|
| Option name | dotnet_style_prefer_collection_expression | |
| Option values | true | when_types_exactly_match |
Prefer to use collection expressions only when types match exactly, for example, List<int> list = new List<int>() { 1, 2 };. |
when_types_loosely_match* |
Prefer to use collection expressions even when types match loosely, for example, IEnumerable<int> list = new List<int>() { 1, 2 };. The targeted type must match the type on the right-hand side or be one of the following types: System.Collections.Generic.IEnumerable, System.Collections.Generic.ICollection, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyCollection, System.Collections.Generic.IReadOnlyList. |
|
false | never |
Disables the rule. | |
| Default option value | when_types_loosely_match* |
*When this option is used, the code fix might change the semantics of your code.
Example
// Code with violation.
List<int> l1 = new List<int>(Enumerable.Range(1, 10));
List<int> m1 = new List<int>(new[] { 1, 2, 3 });
// Fixed code.
List<int> l1 = [.. Enumerable.Range(1, 10)];
List<int> m1 = [.. new[] { 1, 2, 3 }];Suppress a warning
If you want to suppress only a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable IDE0306
// The code that's violating the rule is on this line.
#pragma warning restore IDE0306To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.IDE0306.severity = noneTo disable all of the code-style rules, set the severity for the category Style to none in the configuration file.
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = noneFor more information, see How to suppress code analysis warnings.