ReSharper 2024.1 Help

Code inspection: 'if' statement can be rewritten as '?:' expression

Category

Language Usage Opportunities

ID

ConvertIfStatementToConditionalTernaryExpression

EditorConfig

resharper_convert_if_statement_to_conditional_ternary_expression_highlighting

Default severity

Suggestion

Language

C#

Requires SWA

No

The conditional ?: (ternary) operator in C# is the most elegant way to execute one of two simple expressions depending on the value of a simple boolean expression.

Therefore, if ReSharper encounters an if...else statement in this context, it suggests converting it to a more succinct ?: operator.

Here is an example of a quick-fix suggested by this inspection:

void Foo(string msg1, string msg2, bool flag) { if (flag) Console.WriteLine(msg1); else Console.WriteLine(msg2); }
void Foo(string msg1, string msg2, bool flag) { Console.WriteLine(flag ? msg1 : msg2); }
Last modified: 08 April 2024