rspec/rules/S2692/csharp/rule.adoc
2022-02-04 16:28:24 +00:00

88 lines
1.8 KiB
Plaintext

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.
This rule raises an issue when an ``++IndexOf++`` value retrieved from a ``++string++``, ``++List++`` or array is tested against ``++> 0++``.
This rule also raises an issue when ``++IndexOfAny++``, ``++LastIndexOf++`` or ``++LastIndexOfAny++`` from a ``++string++`` is tested against ``++> 0++``
== Noncompliant Code Example
[source,csharp]
----
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
{
// ...
}
if (name.IndexOf("ish") > 0) // Noncompliant
{
// ...
}
if (name.IndexOf("ae") > 0) // Noncompliant
{
// ...
}
if (Array.IndexOf(stringArray, color) > 0) // Noncompliant
{
// ...
}
----
== Compliant Solution
[source,csharp]
----
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)
{
// ...
}
if (name.IndexOf("ish") >= 0)
{
// ...
}
if (name.Contains("ae"))
{
// ...
}
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[]