Skip to content

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

@GrabYourPitchforks

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

Metadata

Metadata

Assignees

Labels

🏁 Release: .NET 5Work items for the .NET 5 releasebreaking-changeIndicates a .NET Core breaking change

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions