93 lines
2.4 KiB
Plaintext
93 lines
2.4 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,vbnet]
|
|
----
|
|
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 inclusion of a value in a `String`, `List`, or an array, consider using the https://learn.microsoft.com/en-us/dotnet/api/system.string.contains[Contains] method instead.
|
|
|
|
[source,vbnet]
|
|
----
|
|
strings.Contains(someString) ' Boolean result
|
|
----
|
|
|
|
This rule raises an issue when an `IndexOf` value retrieved from a `String`, `List` or array is tested against `> 0`.
|
|
|
|
[source,vbnet]
|
|
----
|
|
strings.IndexOf(someString) > 0 ' Noncompliant: index 0 missing
|
|
----
|
|
|
|
This rule also raises an issue when https://learn.microsoft.com/en-us/dotnet/api/system.string.indexofany[IndexOfAny], https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexof[LastIndexOf] or https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexofany[LastIndexOfAny] from a `String` is tested against `> 0`.
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,vbnet,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
Dim Color As String = "blue"
|
|
Dim Name As String = "ishmael"
|
|
|
|
Dim Strings As New List(Of String)
|
|
Strings.Add(Color)
|
|
Strings.Add(Name)
|
|
Dim StringArray As String() = Strings.ToArray()
|
|
|
|
If Strings.IndexOf(Color) > 0 Then ' Noncompliant
|
|
' ...
|
|
End If
|
|
|
|
If Name.IndexOf("ish") > 0 Then ' Noncompliant
|
|
' ...
|
|
End If
|
|
|
|
If Name.IndexOf("ae") > 0 Then ' Noncompliant
|
|
' ...
|
|
End If
|
|
|
|
If Array.IndexOf(StringArray, Color) > 0 Then ' Noncompliant
|
|
' ...
|
|
End If
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,vbnet,diff-id=1,diff-type=compliant]
|
|
----
|
|
Dim Color As String = "blue"
|
|
Dim Name As String = "ishmael"
|
|
|
|
Dim Strings As New List(Of String)
|
|
Strings.Add(Color)
|
|
Strings.Add(Name)
|
|
Dim StringArray As String() = Strings.ToArray()
|
|
|
|
If Strings.IndexOf(Color) > -1 Then
|
|
' ...
|
|
End If
|
|
|
|
If Name.IndexOf("ish") >= 0 Then
|
|
' ...
|
|
End If
|
|
|
|
If Name.Contains("ae") Then
|
|
' ...
|
|
End If
|
|
|
|
If Array.IndexOf(StringArray, Color) >= 0 Then
|
|
' ...
|
|
End If
|
|
----
|
|
|
|
include::../resources-dotnet.adoc[]
|
|
|
|
include::../rspecator.adoc[]
|