I came across this:
bool Isvalid = isValid & CheckSomething() bool Isvalid = isValid && CheckSomething()
The second case could be a scenario for short circuiting.
So can't we always use just &
instead of &&
?
Use a semicolon to join two related independent clauses in place of a comma and a coordinating conjunction (and, but, or, nor, for, so, yet). Make sure when you use the semicolon that the connection between the two independent clauses is clear without the coordinating conjunction.
A semicolon may be used between independent clauses joined by a connector, such as and, but, or, nor, etc., when one or more commas appear in the first clause. Example: When I finish here, and I will soon, I'll be glad to help you; and that is a promise I will keep.
When a comma separates two complete sentences joined by a conjunction (and, but, or, nor, for, so, or yet) the comma and the conjunction can be replaced with a semicolon. I ate dinner, and I went to the movies. = I ate dinner; I went to the movies. She finished top of her class, but she was struggling to find work.
When using a semicolon to join two independent clauses, do not capitalize the first word of the second independent clause unless the word is a proper noun, e.g., The sky is blue; the birds are singing.
&
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
:
x & y
Logical AND
true
only if x
and y
evaluate to true
x
and y
.x && y
Conditional Logical AND
true
only if x
and y
evaluate to true
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With