Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does StartsWith return the wrong value only on my machine?

The following code works on "everyones" machine, except for mine:

var foo = "caa";
var bar = "ca";
if (foo.StartsWith(bar, false, CultureInfo.GetCultureInfo("no")))
    Console.WriteLine($"{foo} starts with {bar}");
else
{
    Console.WriteLine($"{foo} does not start with {bar}");
}

I’ve tried in on .net 5.0.400, 5.0.403, 6.0.100 – all prints ‘caa does not start with ca’. I’ve not copied the chars from anywhere, I literally type them out.

I understand that this is really just on my computer, but I do not understand why or what is causing this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit: I’m on Windows 10 – OS Build: 19043.1348. nb-NO keyboard, en-US Windows UI language.

Edit: Added if (foo.StartsWith(bar, false, CultureInfo.GetCultureInfo("no") – no change in behavior.

>Solution :

Repro:

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("nb-NO");

var foo = "caa";
var bar = "ca";
if (foo.StartsWith(bar))
{
    Console.WriteLine($"{foo} starts with {bar}");
}
else
{
    Console.WriteLine($"{foo} does not start with {bar}");
}

Since .NET 5, string comparison is done using different string comparison libraries (ICU). In Norwegian, "aa" apparently isn’t the same as "a" + "a". See Behavior changes when comparing strings on .NET 5+.

Edit: not sure why I included the tidbit above, AFAIK this did behave the same on earlier framework versions. Researching…

You’ll want an ordinal (character numeric value) comparison:

foo.StartsWith(bar, StringComparison.Ordinal)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading