C# provides another alternative code syntax to apply the inline if-else condition using conditional ternary operator ?:. The ?: conditional operator returns a value based on the Boolean value returned by evaluating the specified expression.
Syntax:
conditional-expression ? first-result-expression : second-result-expression;
As shown in the above code syntax ?: conditional operator works with three operands. First as a conditional expression that returns the Boolean value based on the specified test condition. Then ?: operator works according to that Boolean value. The first operator symbol i.e. a question mark "?" is equivalent to if statement and works for true Boolean result evaluated from the conditional expression. The second operator i.e. a full colon ":" is equivalent to else statement and works for false Boolean result evaluated from the conditional expression.
Example:
int a = 6;
int b = a % 2;
bool flag = (b == 0) ? true : false;
Response.Write(a.ToString() + " is an even number.");