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 version 15.8

Overview

This style rule concerns with the use of ternary conditional expressions versus an if-else statement for assignments that require conditional logic.

dotnet_style_prefer_conditional_expression_over_assignment

Property Value
Option name dotnet_style_prefer_conditional_expression_over_assignment
Option values true - Prefer assignments with a ternary conditional over an if-else statement

false - Prefer assignments with an if-else statement over a ternary conditional
Default option value true

Example

// 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

See also