Difference between eager operation and short-circuit operation? (| versus || and & versus &&)

后端 未结 7 1993
Happy的楠姐
Happy的楠姐 2020-11-30 15:55

I am (still) learning C# - and I thought I understood the difference between & & && as well as | & ||

7条回答
  •  醉酒成梦
    2020-11-30 16:06

    I think you are getting tripped up because C# has overloaded | and &. Used with numeric primitives then they are bitwise operations. Used with booleans then they are just like || and && except they don't short circuit.

    For example

    bool Foo() {
        return false;
    }
    
    bool Bar() {
         return true;
    }
    
    if(Foo() & Bar()) {
         // do something
    }
    
    // versus
    
    if(Foo() && Bar()) {
          // do something 2
    }
    

    In the above example, the first boolean expression will execute both Foo() and Bar(), but in the second one only Foo() will execute.

    IMO this is one of the worst decisions the C# team has made. It leads to confusing and occasionally subtle errors.

提交回复
热议问题