Use conditional expression for assignment (IDE0045)
Property | Value |
---|---|
Rule ID | IDE0045 |
Title | Use conditional expression for assignment |
Category | Style |
Subcategory | Language rules (expression-level preferences) |
Applicable languages | C# and Visual Basic |
Introduced version | Visual Studio 2017 |
Options | dotnet_style_prefer_conditional_expression_over_assignment |
Overview
This style rule concerns the use of a ternary conditional expression versus an if-else statement for assignments that require conditional logic.
Options
Options specify the behavior that you want the rule to enforce. For information about configuring options, see Option format.
dotnet_style_prefer_conditional_expression_over_assignment
Property | Value | Description |
---|---|---|
Option name | dotnet_style_prefer_conditional_expression_over_assignment | |
Option values | true |
Prefer assignments with a ternary conditional |
false |
Prefer assignments with an if-else statement | |
Default option value | true |
// dotnet_style_prefer_conditional_expression_over_assignment = true
string s = expr ? "hello" : "world";
// dotnet_style_prefer_conditional_expression_over_assignment = false
string s;
if (expr)
{
s = "hello";
}
else
{
s = "world";
}
' dotnet_style_prefer_conditional_expression_over_assignment = true
Dim s As String = If(expr, "hello", "world")
' dotnet_style_prefer_conditional_expression_over_assignment = false
Dim s As String
If expr Then
s = "hello"
Else
s = "world"
End If
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 IDE0045
// The code that's violating the rule is on this line.
#pragma warning restore IDE0045
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.IDE0045.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
Feedback
https://aka.ms/ContentUserFeedback.
În curând: Pe parcursul anului 2024, vom elimina treptat Probleme legate de GitHub ca mecanism de feedback pentru conținut și îl vom înlocui cu un nou sistem de feedback. Pentru mai multe informații, consultați:Trimiteți și vizualizați feedback pentru