Skip to content

[Analyzer suggestion]: Usage of LastIndexOf #44376

Description

@Youssef1313

LastIndexOf behavior has changed as documented in dotnet/docs#21375.
An analyzer that detects a return value of LastIndexOf that's then used as an index to access the character should report a violation.

Example

private static void M1(string s, string s2)
{
    var index = s.LastIndexOf(s2);
   Console.WriteLine(s[index]); // WARNING!! index can be -1 or the length of the string
}

private static void M2(string s, string s2)
{
    var index = s.LastIndexOf(s2);
    if (index > 0)
       Console.WriteLine(s[index]); // WARNING!! index can be the length of the string
}

private static void M3(string s, string s2)
{
    var index = s.LastIndexOf(s2);
    if (index > 0 && index < s.Length)
       Console.WriteLine(s[index]); // NO WARNING!
}

private static void M4(string s, string s2)
{
    if (string.IsNullOrEmpty(s2)) return;
    // or IsNullOrWhiteSpace, or s2 == "", or s2.Length == 0

    var index = s.LastIndexOf(s2);
    if (index > 0)
       Console.WriteLine(s[index]); // NO WARNING!
}

cc: @mavasani

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions