Understanding String Comparison Behavior

I need to convert some string comparisons from vb to C #. The vb code uses> and <operators. I want to replace this with standard string string comparison methods. But, there the behavior I do not understand. To reproduce this, I have this test

[TestMethod]
public void TestMethod2()
{
    string originalCulture = CultureInfo.CurrentCulture.Name; // en-GB

    var a = "d".CompareTo("t");  // returns -1
    var b = "T".CompareTo("t");  // returns 1

    Assert.IsTrue(a < 0, "Case 1");
    Assert.IsTrue(b <= 0, "Case 2");
}

Can someone explain why b returns 1. My real understanding is that if it is case sensitive, then "T" must be preceded by "t" in sort order, i.e. -1. If it is case insensitive, it will be the same as 0

(FYI.Net Framework 4.5.2)

Many thanks

+6
source share
3 answers

The lower scale is in front of the upper case. This is true for both en-GB and InvariantCulture.

ASCII, CompareOptions.Ordinal

. :

repl.it:

using System;
using System.Globalization;
using System.Collections.Generic;

class MainClass
{
    public static void Main(string[] args)
    {

        //All the following case sensitive comparisons puts d before D
        Console.WriteLine("D".CompareTo("d"));
        Console.WriteLine(String.Compare("D", "d", false));
        Console.WriteLine(String.Compare("D", "d", false, CultureInfo.InvariantCulture));

        //All the following case sensitive comparisons puts capital D before small letter d
        Console.WriteLine(String.Compare("D", "d", CultureInfo.InvariantCulture, CompareOptions.Ordinal));

        //The following is case insensitive
        Console.WriteLine(String.Compare("D", "d", true));

        //The default string ordering in my case is d before D
        var list = new List<string>(new[] { "D", "d" });
        list.Sort();
        foreach (var s in list)
        {
            Console.WriteLine(s);
        }
    }
}

//Results on repl.it
//Mono C# compiler version 4.0.4.0
//   
//1
//1
//1
//-32
//0
//d
//D

.

+1
0

CompareTo (strA, strB),

CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);

For lower letters, en-GB is less than uppercase.

0
source

All Articles