106 lines
2.7 KiB
Plaintext

== Why is this an issue?
Most checks against an https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof[IndexOf] value compare it with -1 because *0 is a valid index*.
[source,csharp]
----
strings.IndexOf(someString) == -1 // Test for "index not found"
strings.IndexOf(someString) < 0 // Test for "index not found"
strings.IndexOf(someString) >= 0 // Test for "index found"
----
Any checks which look for values `> 0` ignore the first element, which is likely a bug. If the intent is merely to check the inclusion of a value in a `string`, `List`, or array, consider using the https://learn.microsoft.com/en-us/dotnet/api/system.string.contains[Contains] method instead.
[source,csharp]
----
strings.Contains(someString) // bool result
----
This rule raises an issue when the output value of any of the following methods is tested against `> 0`:
* https://learn.microsoft.com/en-us/dotnet/api/system.collections.ilist.indexof[IndexOf], applied to `string`, list or array
* https://learn.microsoft.com/en-us/dotnet/api/system.string.indexofany[IndexOfAny], applied to a `string`
* https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexof[LastIndexOf], applied to a `string`, list or array
* https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexofany[LastIndexOfAny], applied to a `string`
[source,csharp]
----
someArray.IndexOf(someItem) > 0 // Noncompliant: index 0 missing
someString.IndexOfAny(charsArray) > 0 // Noncompliant: index 0 missing
someList.LastIndexOf(someItem) > 0 // Noncompliant: index 0 missing
someString.LastIndexOf(charsArray) > 0 // Noncompliant: index 0 missing
----
== How to fix it
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
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,diff-id=1,diff-type=compliant]
----
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)
{
// ...
}
----
include::../resources-dotnet.adoc[]
include::../rspecator.adoc[]