开发者

Usage of '&' versus '&&'

开发者 https://www.devze.com 2023-02-22 10:05 出处:网络
I came across this: bool Isvalid = isValid & CheckSomething() bool Isvalid = isValid 开发者_JS百科&& CheckSomething()

I came across this:

bool Isvalid = isValid & CheckSomething()

bool Isvalid = isValid 开发者_JS百科&& CheckSomething()

The second case could be a scenario for short circuiting.

So can't we always use just & instead of &&?


& is a bitwise AND, meaning that it works at the bit level. && is a logical AND, meaning that it works at the boolean (true/false) level. Logical AND uses short-circuiting (if the first part is false, there's no use checking the second part) to prevent running excess code, whereas bitwise AND needs to operate on every bit to determine the result.

You should use logical AND (&&) because that's what you want, whereas & could potentially do the wrong thing. However, you would need to run the second method separately if you wanted to evaluate its side effects:

var check = CheckSomething();
bool IsValid = isValid && check;


C# has two types of logical conjunction (AND) operators for bool:

  1. x & y Logical AND

    • Results in true only if x and y evaluate to true
    • Evaluates both x and y.
  2. x && y Conditional Logical AND

    • Results in true only if x and y evaluate to true
    • Evaluates x first, and if x evaluates to false, it returns false immediately without evaluating y (short-circuiting)

So if you rely on both x and y being evaluated you can use the & operator, although it is rarely used and harder to read because the side-effect is not always clear to the reader.

Note: The binary & operator also exists for integer types (int, long, etc.) where it performs bitwise logical AND.


In && the second expression is only evaluated if the first one is true.

And & is just a way to concatenate the two expressions, like true & true = true, true & false = false etc.


I believe you are missing something. In the second scenario CheckSomething is not evaluated if isValid is false

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

http://msdn.microsoft.com/en-us/library/2a723cdk(v=vs.71).aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消