Search code examples
c#.net-core.net-6.0.net-4.8

Weird String.StartsWith and .Contains behaviour after upgrade from .NET Framework 4.8 to .NET 6


We are currently updating an application from .Net Framework 4.8 to .NET 6 and there is one particular thing that has me puzzled:

"MyString".StartsWith("\x01");

In .Net Framework this would return false. As I would expect, as the strings first character is not '\x01'

But in .Net 6 (also with .Net 5 already) this evaluates to true? We couldn't find any explanation on why this behaviour has changed, do you know any resource we could refer to?

We figured out, this can be solved by using the new overload of StartsWith(char) instead of the (old?) one with the string parameter.

The upgrade path did not replace those automatically, so I would expect the behaviour would be the same as well.


Solution

  • This is because .NET changed from using NLS to ICU, and, performs culture aware comparisons by default for StartsWith(string). There is some background on the changes in the .NET runtime repository.

    Consider using ordinal comparisons:

    "MyString".StartsWith("\x01", StringComparison.Ordinal);
    

    Which will do what you expect.