rspec/rules/S127/csharp/rule.adoc

45 lines
797 B
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
2020-06-30 10:16:44 +02:00
include::../description.adoc[]
== How to fix it
2020-06-30 10:16:44 +02:00
It's generally recommended to only update the loop counter in the loop declaration. If skipping elements or iterating at a different pace based on a condition is needed, consider using a while loop or a different structure that better fits the needs.
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
2020-06-30 10:16:44 +02:00
----
for (int i = 1; i <= 5; i++)
2020-06-30 10:16:44 +02:00
{
Console.WriteLine(i);
if (condition)
2020-06-30 10:16:44 +02:00
{
i = 20;
2020-06-30 10:16:44 +02:00
}
}
----
==== Compliant solution
2020-06-30 10:16:44 +02:00
[source,csharp,diff-id=1,diff-type=compliant]
2020-06-30 10:16:44 +02:00
----
int i = 1;
while (i <= 5)
2020-06-30 10:16:44 +02:00
{
Console.WriteLine(i);
if (condition)
2020-06-30 10:16:44 +02:00
{
i = 20;
}
else
{
i++;
2020-06-30 10:16:44 +02:00
}
}
----
include::../rspecator.adoc[]