Use collection expression for fluent (IDE0305)

Property Value
Rule ID IDE0305
Title Use collection expression for fluent
Category Style
Subcategory Language rules (expression-level preferences)
Applicable languages C# 12+
Options dotnet_style_prefer_collection_expression

Overview

This rule flags places where a collection is built in a fluent manner, that is, where methods like Add(), AddRange(), AsSpan(), ToList(), and ToArray() are chained. Instead, a collection expression could be used to initialize the collection. For example, x.AddRange(y).Add(z).AsSpan() is converted to [x, ..y, z].

Options

Options specify the behavior that you want the rule to enforce. For information about configuring options, see Option format.

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[] { 1, 2, 3 }.ToList();.
when_types_loosely_match
(.NET 9 and later versions)*
Prefer to use collection expressions even when types match loosely, for example, IEnumerable<int> list = new[] { 1, 2, 3 }.ToList();. The targeted type must match the type on the right-hand side or be one of the following types: IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>.
false | never Disables the rule.
Default option value true in .NET 8
when_types_loosely_match in .NET 9 and later versions

*The code fix when this option is used might change the semantics of your code.

Example

// Code with violation.
List<int> i = new[] { 1, 2, 3 }.ToList();
IEnumerable<int> j = new[] { 1, 2, 3 }.ToList();

// Fixed code.
List<int> i = [1, 2, 3];
IEnumerable<int> j = [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 IDE0305
// The code that's violating the rule is on this line.
#pragma warning restore IDE0305

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.IDE0305.severity = none

To 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 = none

For more information, see How to suppress code analysis warnings.

See also