What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:
Conditional ?: Operator
While the above answers are valid, and I agree with readability being important, there are 2 further points to consider:
This makes it particularly concise to use the ternary:
string GetDrink(DayOfWeek day)
=> day == DayOfWeek.Friday
? "Beer" : "Tea";
If you have types T1
and T2
that can both be implicitly converted to T
, then the below does not work:
T GetT() => true ? new T1() : new T2();
(because the compiler tries to determine the type of the ternary expression, and there is no conversion between T1
and T2
.)
On the other hand, the if/else
version below does work:
T GetT()
{
if (true) return new T1();
return new T2();
}
because T1
is converted to T
and so is T2