Redigeeri

Jagamisviis:


Use object initializers (IDE0017)

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

Overview

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

Options

The option value for this rule specifies whether or not initializers are desired.

For more information about configuring options, see Option format.

dotnet_style_object_initializer

Property Value Description
Option name dotnet_style_object_initializer
Option values true Prefer objects to be initialized using object initializers when possible
false Prefer objects to not be initialized using object initializers
Default option value true
// dotnet_style_object_initializer = true
var c = new Customer() { Age = 21 };

// dotnet_style_object_initializer = false
var c = new Customer();
c.Age = 21;
' dotnet_style_object_initializer = true
Dim c = New Customer() With {.Age = 21}

' dotnet_style_object_initializer = false
Dim c = New Customer()
c.Age = 21

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 IDE0017
// The code that's violating the rule is on this line.
#pragma warning restore IDE0017

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

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