61 lines
2.2 KiB
Plaintext
61 lines
2.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
https://en.wikipedia.org/wiki/Short-circuit_evaluation[Short-circuit evaluation] is an evaluation strategy for https://en.wikipedia.org/wiki/Logical_connective[Boolean operators], that doesn't evaluates the second argument of the operator if it is not needed to determine the result of the operation.
|
|
|
|
C# provides logical operators that implement short-circuit evaluation: `&&` and `||`, as well as non-short-circuit versions: `&` and `|`. Unlike short-circuit operators, non-short-circuit ones evaluate both operands and afterwards perform the logical operation.
|
|
|
|
For example `false && FunctionCall()` always results in `false`, even when `FunctionCall` invocation would raise an exception. Instead, `false & FunctionCall()` also evaluates `FunctionCall()`, and results in an exception if `FunctionCall()` invocation raises an exception.
|
|
|
|
Similarly, `true || FunctionCall()` always results in `true`, no matter what the return value of `FunctionCall()` would be.
|
|
|
|
The use of non-short-circuit logic in a boolean context is likely a mistake - one that could cause serious program errors as conditions are evaluated under the wrong circumstances.
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
if (GetTrue() | GetFalse()) // Noncompliant: both sides evaluated
|
|
{
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
if (GetTrue() || GetFalse()) // Compliant: short-circuit logic used
|
|
{
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators[Boolean logical operators - AND, OR, NOT, XOR]
|
|
* https://en.wikipedia.org/wiki/Short-circuit_evaluation[Short-circuit evaluation]
|
|
* https://en.wikipedia.org/wiki/Logical_connective[Boolean operators]
|
|
|
|
=== Articles & blog posts
|
|
|
|
* https://ericlippert.com/2015/11/02/when-would-you-use-on-a-bool/[Eric Lippert's blog - When would you use & on a bool?]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|