Benefits of using the conditional ?: (ternary) operator

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

    I usually choose a ternary operator when I'd have a lot of duplicate code otherwise.

    if (a > 0)
        answer = compute(a, b, c, d, e);
    else
        answer = compute(-a, b, c, d, e);
    

    With a ternary operator, this could be accomplished with the following.

    answer = compute(a > 0 ? a : -a, b, c, d, e); 
    
    0 讨论(0)
  • 2020-11-22 07:49

    A really cool usage is:

    x = foo ? 1 :
        bar ? 2 :
        baz ? 3 :
              4;
    
    0 讨论(0)
  • 2020-11-22 07:50

    If you need multiple branches on the same condition, use an if:

    if (A == 6)
      f(1, 2, 3);
    else
      f(4, 5, 6);
    

    If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:

    f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );
    

    Also, you can use the ternary operator in initialization.

    const int i = (A == 6)? 1 : 4;
    

    Doing that with if is very messy:

    int i_temp;
    if (A == 6)
       i_temp = 1;
    else
       i_temp = 4;
    const int i = i_temp;
    

    You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 08:00

    The conditional operator is great for short conditions, like this:

    varA = boolB ? valC : valD;
    

    I use it occasionally because it takes less time to write something that way... unfortunately, this branching can sometimes be missed by another developer browsing over your code. Plus, code isn't usually that short, so I usually help readability by putting the ? and : on separate lines, like this:

    doSomeStuffToSomething(shouldSomethingBeDone()
        ? getTheThingThatNeedsStuffDone()
        : getTheOtherThingThatNeedsStuffDone());
    

    However, the big advantage to using if/else blocks (and why I prefer them) is that it's easier to come in later and add some additional logic to the branch,

    if (shouldSomethingBeDone()) {
        doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
        doSomeAdditionalStuff();
    } else {
    doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
    }
    

    or add another condition:

    if (shouldSomethingBeDone()) {
        doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
        doSomeAdditionalStuff();
    } else if (shouldThisOtherThingBeDone()){
        doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
    }
    

    So, in the end, it's about convenience for you now (shorter to use :?) vs. convenience for you (and others) later. It's a judgment call... but like all other code-formatting issues, the only real rule is to be consistent, and be visually courteous to those who have to maintain (or grade!) your code.

    (all code eye-compiled)

    0 讨论(0)
提交回复
热议问题