rspec/rules/S2583/csharp/rule.adoc
2023-08-11 09:56:44 +02:00

125 lines
2.8 KiB
Plaintext

== Why is this an issue?
include::../description.adoc[]
In the case below, the call of `Dispose()` never happens.
[source,csharp]
----
var a = false;
if (a)
{
Dispose(); // Never reached
}
----
=== Exceptions
This rule will not raise an issue in either of these cases:
* When the condition is a single `const bool`
+
[source,csharp]
----
const bool debug = false;
//...
if (debug)
{
// Print something
}
----
* When the condition is the literal `true` or `false`.
In these cases, it is obvious the code is as intended.
== How to fix it
The conditions should be reviewed to decide whether:
* to update the condition or
* to remove the condition.
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
public void Sample(bool b)
{
bool a = false;
if (a) // Noncompliant: The true branch is never reached
{
DoSomething(); // Never reached
}
if (!a || b) // Noncompliant: "!a" is always "true" and the false branch is never reached
{
DoSomething();
}
else
{
DoSomethingElse(); // Never reached
}
var c = "xxx";
var res = c ?? "value"; // Noncompliant: c is always not null, "value" is never used
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
public void Sample(bool b)
{
bool a = false;
if (Foo(a)) // Condition was updated
{
DoSomething();
}
if (b) // Parts of the condition were removed.
{
DoSomething();
}
else
{
DoSomethingElse();
}
var c = "xxx";
var res = c; // ?? "value" was removed
}
----
include::../see.adoc[]
=== Documentation
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#conditional-logical-and-operator-[Conditional logical AND operator &&]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#conditional-logical-or-operator-[Conditional logical OR operator ||]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator[?? and ??= operators - the null-coalescing operators]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Change this condition so that it does not always evaluate to "[true|false]". Some code paths are unreachable.
* Change this expression which always evaluates to the same result. Some code paths are unreachable.
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]