Using the ternary operator for multiple operations

后端 未结 5 1827
萌比男神i
萌比男神i 2020-12-30 02:44

How can I use the ternary ? : condition to perform multiple operations, if expression is true/false?

wbsource = (exp) ? (Do one thing) : (Do secon

5条回答
  •  Happy的楠姐
    2020-12-30 03:26

    Why can't I perform three operations between ? and :

    Because these are operands, which are expressions. Each expression evaluates a value; you want multiple statements. From Eric Lippert's blog post about foreach vs ForEach:

    The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects.

    The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect. The call site of this thing would look an awful lot like an expression (though, admittedly, since the method is void-returning, the expression could only be used in a “statement expression” context.)

    You should absolutely write this using an if block. It's clearer.

    If you really, really want to use the conditional operator for this, you could write:

    // Please, please don't use this.
    Func x = () => {
        Properties.Settings.Default.filename = fp;
        Properties.Settings.Default.Save();
        return fp;
    };
    
    string filename = fp == null ? Properties.Settings.Default.file : x();
    

提交回复
热议问题