Search code examples
c#ends-with

C# EndsWith sometimes gives false results


"Cs".EndsWith("s") and "cs".EndsWith("s") gives me "false".

I put together a simple console application to present the problem:

string[] strings = { "s", "As", "Bs", "Cs", "Ds", "Es", "as", "bs", "cs", "ds", "es", "AAs", "ABs", "ACs", "ADs", "AEs" };
foreach (string str in strings)
  Console.WriteLine(str + " ends with 's': " + str.EndsWith("s"));
Console.ReadKey();

The result is this:

s ends with 's': True
As ends with 's': True
Bs ends with 's': True
Cs ends with 's': False
Ds ends with 's': True
Es ends with 's': True
as ends with 's': True
bs ends with 's': True
cs ends with 's': False
ds ends with 's': True
es ends with 's': True
AAs ends with 's': True
ABs ends with 's': True
ACs ends with 's': False
ADs ends with 's': True
AEs ends with 's': True

I have tried changing the target framework: (VS2013)

  • all 4.x versions produced this error
  • on .NET 3.5, 3.0, 2.0 worked well.

Also tried with VS2022 Preview (on 2 different computers) with .NET 6.0 but produced the same problems.

In dotnetfiddle (.NET 4.7.2) it works well... :-O

Can you help me where shall I look for the solution? (settings, installed softwares, etc.)

Thanks in advance.


Solution

  • In general the easiest way in your case is to tell the string comparer it should use ordinal comparison like so:

    str.EndsWith("s", StringComparison.Ordinal)
    

    As people in the comments allready explained, most string-functions work with the current culture, and that appears to be hungarian, thats why you are getting theese results.

    Another benefit is, that ordinal comparison is by far the fastest.