Peter Trifanov d953a8c265
Modify S1121: Migrate to LayC - Assignments should not be made from within sub-expressions
Co-authored-by: Fred Tingaud <frederic.tingaud@sonarsource.com>
2023-10-13 19:17:01 +02:00

100 lines
1.8 KiB
Plaintext

== Why is this an issue?
include::../description.adoc[]
=== Exceptions
Assignments inside lambda and delegate expressions are allowed.
[source,csharp]
----
var result = Foo(() =>
{
int x = 100; // dead store, but ignored
x = 200;
return x;
}
----
The rule also ignores the following patterns:
* Chained assignments
[source,csharp]
----
var a = b = c = 10;
----
* Assignments that are part of a condition of an `if` statement or a loop
[source,csharp]
----
while ((val = GetNewValue()) > 0)
{
...
}
----
* Assignment in the right-hand side of a coalescing operator
[source,csharp]
----
private MyClass instance;
public MyClass Instance => instance ?? (instance = new MyClass());
----
== How to fix it
include::../how-to-fix-it.adoc[]
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
if (string.IsNullOrEmpty(result = str.Substring(index, length))) // Noncompliant
{
// do something with "result"
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
var result = str.Substring(index, length);
if (string.IsNullOrEmpty(result))
{
// do something with "result"
}
----
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
=== on 21 Jan 2016, 11:09:06 Dinesh Bolkensteyn wrote:
This rule doesn't cover the R# compiler warning (which is out of the box in Roslyn).
See \https://msdn.microsoft.com/en-us/library/c1sde1ax.aspx for details on how that one behaves.
As this more generalized rule is way more crappy, I'm disabling it by default for C#
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]