Benefits of using the conditional ?: (ternary) operator

后端 未结 17 1005
孤街浪徒
孤街浪徒 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:43

    With C# 7, you can use the new ref locals feature to simplify the conditional assignment of ref-compatible variables. So now, not only can you do:

    int i = 0;
    
    T b = default(T), c = default(T);
    
    // initialization of C#7 'ref-local' variable using a conditional r-value⁽¹⁾
    
    ref T a = ref (i == 0 ? ref b : ref c);
    

    ...but also the extremely wonderful:

    // assignment of l-value⁽²⁾ conditioned by C#7 'ref-locals'
    
    (i == 0 ? ref b : ref c) = a;
    

    That line of code assigns the value of a to either b or c, depending on the value of i.



    Notes
    1. r-value is the right-hand side of an assignment, the value that gets assigned.
    2. l-value is the left-hand side of an assignment, the variable that receives the assigned value.

提交回复
热议问题