3

Normally if a character A is smaller than character B, then I'd expect in string comparison:

AB < BA

And indeed, in a dictionary you can find AB words before BA words.

Somehow this is not the case for underscores

Small program; use copy paste to check

public static void Main()
{
    IComparer<string> comp = Comparer<string>.Default;
    Console.WriteLine("Compare '-' with '_': " + comp.Compare("-", "_").ToString());
    Console.WriteLine("Compare '--' with '-_': " + comp.Compare("--", "-_").ToString());
    Console.WriteLine("Compare '-_' with '_-': " + comp.Compare("-_", "_-").ToString());
}

The output is:

Compare '-' with '_': -1
Compare '--' with '-_': -1
Compare '-_' with '_-': 1

The last value returns +1
So:

"-"< "_"              // minus is less than underscore
"-_" > "_-"           // minus underscore MORE THAN underscore minus

This behaviour occurs when using the default string comparer. StringComparer.Ordinal works as expected.

Is this an error in the default string comparer?

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • This behavior is culture-specific ([demo](https://ideone.com/4DfXBF)). – Sergey Kalinichenko Dec 08 '17 at 13:09
  • @dasblinkenlight then probably we wrongly marked that as duplicate? – Evk Dec 08 '17 at 13:10
  • @dasblinkenlight on the other hand - site you linked uses gmcs compiler (stated on the right), which is mono compiler, so that might be the difference and not culture. I tried on .NET (not mono) with "en-us" culture (used at site you linked) - and it produces the same results as in question. – Evk Dec 08 '17 at 13:17
  • @Evk I tried this on my Mac using MS Dev Studio community edition, and I get the same results as on ideone. Mac's version uses mono, so I think you're right about it being mono-vs-microsoft implementation difference. – Sergey Kalinichenko Dec 08 '17 at 13:44
  • In which culture is minus before underscore, but "minus underscore" after "underscore minus" in the dictionary? – Harald Coppoolse Dec 08 '17 at 16:06

0 Answers0