Inconsistent behavior of C# CompareTo()

Bob 1 Reputation point
2022-09-21T02:32:43.86+00:00

I'm writing a sorting algorithm in C#. The algorithm is written in one project (call it the "Sort project"). I've built another project (call it the "Scratch project") to use as a baseline to compare the results of CompareTo(). I get different results with the CompareTo() method in one project than I get in the other project. For example, "'1".CompareTo("0 ") gives a 1 in the Sort project but a -1 in the Scratch project. "-".CompareTo(" ") gives a -1 in the Sort project but a 1 in the Scratch project. "-".CompareTo("0") actually returns a 0 in the Sort project but a -1 in the Scratch project. The list goes on. However, for comparisons of completely numeric (1-9) and alphabetical (a-z,A-Z) characters seems to give the same results in both projects. I'm not aware of any culture specific settings, languages, or anything unusual in use in either of my projects. I'll include some screenshots but I can include more. I'm using Visual Studio Community 2022 (17.3.3) with .NET 4.8.04161.

Example 01 in Scratch project
Example 01 in Sort project

Developer technologies | .NET | .NET Runtime
Developer technologies | Visual Studio | Debugging
Developer technologies | Visual Studio | Testing
Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2022-09-21T10:21:16.363+00:00

    It seems that you are using .NET 6 or Core in the first case, which performs a "String sort" (https://learn.microsoft.com/en-us/dotnet/api/system.globalization.compareoptions).

    To obtain the same results in both of environments, try this comparison:

    string.Compare( test1, test2, CultureInfo.CurrentCulture, CompareOptions.StringSort )

    or use the appropriate values for CultureInfo and CompareOptions.


  2. Bob 1 Reputation point
    2022-10-01T04:10:34.713+00:00

    I think you're right--I was just coming to the same conclusion. I think I want to be using CompareOptions.Ordinal in my specific circumstance. I'm using Compare() to sort items in a list. With the ordinal sort my compares have been consistent.

    The comparison call that worked for me was
    if (String.Compare(stringOne, stringTwo, CultureInfo.CurrentCulture, CompareOptions.Ordinal) <= 0) { // do things }

    Thanks for your help everyone!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.