Skip to content

Breaking change: Improved String.LastIndexOf handling of empty values #21372

Closed

Description

@GrabYourPitchforks

Breaking change: Improved String.LastIndexOf handling of empty values

string.LastIndexOf and related APIs now return correct values when searching for a zero-length (or zero-length equivalent) substring within a larger string.

Version introduced

.NET 5.0

Old behavior

In .NET Framework and .NET Core, string.LastIndexOf and related APIs could return an incorrect value when the caller searches for a zero-length substring.

Console.WriteLine("Hello".LastIndexOf("")); // prints '4' (incorrect)

ReadOnlySpan<char> span = "Hello";
Console.WriteLine(span.LastIndexOf("")); // prints '0' (incorrect)

New behavior

Beginning with .NET 5.0, these APIs return the correct value for LastIndexOf.

Console.WriteLine("Hello".LastIndexOf("")); // prints '5' (correct)

ReadOnlySpan<char> span = "Hello";
Console.WriteLine(span.LastIndexOf("")); // prints '5' (correct)

In these examples, 5 is the correct answer because "Hello".Substring(5) and "Hello".AsSpan().Slice(5) both produce an empty string, which is trivially equal to the empty substring being sought.

Reason for change

This change was part of an overall bug fixing effort around string handling for .NET 5. This also helps unify our behavior between Windows and non-Windows platforms. See dotnet/runtime#13383 and dotnet/runtime#13382 for more information.

Recommended action

Developers needn't take any action. The .NET 5.0 runtime provides the new behaviors automatically.

There is no compatibility switch to restore the old behavior.

Category

  • Core .NET libraries

Affected APIs


Issue metadata

  • Issue type: breaking-change

Activity

  1. added
    breaking-change
    on Nov 6, 2020
  2. added
    🏁 Release: .NET 5
    and removed
    ⌚ Not Triaged
    on Nov 7, 2020
  3. changed the title [-]reaking change: Improved String.LastIndexOf handling of empty values[/-] [+]Breaking change: Improved String.LastIndexOf handling of empty values[/+] on Nov 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

🏁 Release: .NET 5breaking-change

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions