Benefits of using the conditional ?: (ternary) operator

后端 未结 17 1210
孤街浪徒
孤街浪徒 2020-11-22 06:55

What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:

Conditional ?: Operator

17条回答
  •  野性不改
    2020-11-22 07:52

    While the above answers are valid, and I agree with readability being important, there are 2 further points to consider:

    1. In C#6, you can have expression-bodied methods.

    This makes it particularly concise to use the ternary:

    string GetDrink(DayOfWeek day) 
       => day == DayOfWeek.Friday
          ? "Beer" : "Tea";
    
    1. Behaviour differs when it comes to implicit type conversion.

    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

提交回复
热议问题