Skip to main content

Ternary expression can be used

In This Article

CodeRush Classic shows the Ternary expression can be used code issue if an if/else conditional expression can be converted into a ternary expression.

#Fix

Convert the if/else conditional expression to a ternary expression.

#Purpose

Highlights the if/else conditional expressions, which can be converted into a ternary expression to improve code readability.

#Example

private string _Text;
public void SetText(string text)
{
    if (text == null)
        return;
    _Text = text;if (text.Length > 10)
        Console.WriteLine(text.Substring(0, 10) + "...");
    else
        Console.WriteLine(text);
}

Fix:

private string _Text;
public void SetText(string text)
{
    if (text == null)
        return;
    _Text = text;
    Console.WriteLine(text.Length > 10 ? text.Substring(0, 10) + "..." : text);
}