A clear, layman's explanation of the difference between | and || in c#?

后端 未结 11 547
余生分开走
余生分开走 2020-12-02 12:51

Ok, so I\'ve read about this a number of times, but I\'m yet to hear a clear, easy to understand (and memorable) way to learn the difference between:

if (x |         


        
11条回答
  •  臣服心动
    2020-12-02 13:40

    Strongly recommend to read this article from Dotnet Mob

    For OR logical operation if any of it's operand is evaluated to true then whole expression is evaluated to true

    this is what || Operator does - it skips the remaining evaluation when it found a true. While | Operator evaluate it's complete operands to asses the value of whole expression.

    if(true||Condition1())//it skip Condition1()'s evaluation
    {
    //code inside will be executed
    }
    if(true|Condition1())//evaluates Condition1(), but actually no need for that
    {
    //code inside will be executed
    }
    

    It is better to use Short Circuited version of Logical Operator Whether it is OR(||) or AND(&&) Operator.


    Consider the following Code Snippet

    int i=0;
    if(false||(++i<10))//Now i=1
    {
    //Some Operations
    }
    if(true||(++i<10))//i remains same, ie 1
    {}
    

    This effect is called side effect, actually seen in right side of expression in short circuited logical operators

    Reference : Short-circuit Evaluation in C#

提交回复
热议问题