rspec/rules/S2692/csharp/rule.adoc

88 lines
1.8 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
Most checks against an ``++IndexOf++`` value compare it with -1 because 0 is a valid index. Any checks which look for values ``++> 0++`` ignore the first element, which is likely a bug. If the intent is merely to check inclusion of a value in a ``++string++``, ``++List++``, or an array, consider using the ``++Contains++`` method instead.
2020-06-30 12:48:07 +02:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
This rule raises an issue when an ``++IndexOf++`` value retrieved from a ``++string++``, ``++List++`` or array is tested against ``++> 0++``.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
This rule also raises an issue when ``++IndexOfAny++``, ``++LastIndexOf++`` or ``++LastIndexOfAny++`` from a ``++string++`` is tested against ``++> 0++``
2020-06-30 12:48:07 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
string color = "blue";
string name = "ishmael";
List<string> strings = new List<string>();
strings.Add(color);
strings.Add(name);
string[] stringArray = strings.ToArray();
if (strings.IndexOf(color) > 0) // Noncompliant
{
// ...
}
2021-01-23 04:07:47 +00:00
2020-06-30 12:48:07 +02:00
if (name.IndexOf("ish") > 0) // Noncompliant
{
// ...
}
2021-01-23 04:07:47 +00:00
2020-06-30 12:48:07 +02:00
if (name.IndexOf("ae") > 0) // Noncompliant
{
// ...
}
2021-01-23 04:07:47 +00:00
2020-06-30 12:48:07 +02:00
if (Array.IndexOf(stringArray, color) > 0) // Noncompliant
{
// ...
}
----
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
string color = "blue";
string name = "ishmael";
List<string> strings = new List<string> ();
strings.Add(color);
strings.Add(name);
string[] stringArray = strings.ToArray();
if (strings.IndexOf(color) > -1)
{
// ...
}
2021-01-23 04:07:47 +00:00
2020-06-30 12:48:07 +02:00
if (name.IndexOf("ish") >= 0)
{
// ...
}
2021-01-23 04:07:47 +00:00
2020-06-30 12:48:07 +02:00
if (name.Contains("ae"))
{
// ...
}
2021-01-23 04:07:47 +00:00
2020-06-30 12:48:07 +02:00
if (Array.IndexOf(stringArray, color) >= 0)
{
// ...
}
----
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[]