60 lines
1.4 KiB
Plaintext
60 lines
1.4 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``.
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
Dim color As String = "blue"
|
|
Dim name As String = "ishmael"
|
|
|
|
Dim strings As New List(Of String) = New List(Of String)
|
|
strings.Add(color)
|
|
strings.Add(name)
|
|
Dim stringArray As String() = strings.ToArray()
|
|
|
|
If (strings.IndexOf(color) > 0) ' Noncompliant
|
|
' ...
|
|
End If
|
|
|
|
If (name.IndexOf("ish") > 0) ' Noncompliant
|
|
' ...
|
|
End If
|
|
|
|
If (name.IndexOf("ae") > 0) ' Noncompliant
|
|
' ...
|
|
End If
|
|
|
|
If (Array.IndexOf(stringArray, color) > 0) ' Noncompliant
|
|
' ...
|
|
End If
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
Dim color As String = "blue"
|
|
Dim name As String = "ishmael"
|
|
|
|
Dim strings As New List(Of String) = New List(Of String)
|
|
strings.Add(color)
|
|
strings.Add(name)
|
|
Dim stringArray As String() = strings.ToArray()
|
|
|
|
If (strings.IndexOf(color) > -1)
|
|
' ...
|
|
End If
|
|
|
|
If (name.IndexOf("ish") >= 0)
|
|
' ...
|
|
End If
|
|
|
|
If (name.Contains("ae"))
|
|
' ...
|
|
End If
|
|
|
|
If (Array.IndexOf(stringArray, color) >= 0)
|
|
' ...
|
|
End If
|
|
----
|