Use collection initializers (IDE0028)

Property Value
Rule ID IDE0028
Title Use collection initializers
Category Style
Subcategory Language rules (expression-level preferences)
Applicable languages C# and Visual Basic
Options dotnet_style_collection_initializer

Overview

This style rule concerns the use of collection initializers for collection initialization.

Options

Set the value of the associated option for this rule to specify whether or not collection initializers are preferred when initializing collections.

For more information about configuring options, see Option format.

dotnet_style_collection_initializer

Property Value Description
Option name dotnet_style_collection_initializer
Option values true Prefer collections to be initialized using collection initializers when possible
false Prefer collections to not be initialized using collection initializers
Default option value true
// dotnet_style_collection_initializer = true
var list = new List<int> { 1, 2, 3 };

// dotnet_style_collection_initializer = false
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
' dotnet_style_collection_initializer = true
Dim list = New List(Of Integer) From {1, 2, 3}

' dotnet_style_collection_initializer = false
Dim list = New List(Of Integer)
list.Add(1)
list.Add(2)
list.Add(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 IDE0028
// The code that's violating the rule is on this line.
#pragma warning restore IDE0028

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

[*.{cs,vb}]
dotnet_diagnostic.IDE0028.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