rspec/rules/S2692/csharp/rule.adoc

62 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-01-22 04:06:24 +00: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-01-22 04:06:24 +00:00
This rule raises an issue when an ``IndexOf`` value retrieved from a ``string``, ``List`` or array is tested against ``> 0``.
2020-06-30 12:48:07 +02:00
== Noncompliant Code Example
----
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
----
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)
{
// ...
}
----