I have 2 questions about the CompareTo() method in c#:
- I read this method compares between the letters in two strings and returns the difference between the Unicode values of the first pair of letters, that aren't the same in the both strings. But when I run it, it always returns -1, 0, or 1. For example:
string s1, s2;
s1 = "AARZNML";
s2 = "AARZK";
Console.WriteLine(s1.CompareTo(s2));
In the book it was said that the code must return -24, but it returns -1, when I run it.
- What is
CompareTo()method supposed to return when I compare a string with uppercase letters and a string with lowercase lowercase. For example I ran this code:
string s1, s2;
s1 = "A";
s2 = "a";
Console.WriteLine(s1.CompareTo(s2));
and it returned 1, how can it be? Because 'A' is before 'a' in ASCII Table.
Because the only contract
string.CompareTo(string? strB)has is that it:strB.strB.strB. -or-strBis null.So implementation is free to return any integer matching the rules. It is quite common to implement
IComparable.CompareToin a way that it uses only those 3 numbers (-1, 0, 1) as return values but this is not guaranteed in general.Note that:
I.e. the following:
Prints
aand thenA, so in default ordering (on my machine with my default culture)Afollowsa, so the result is ofComapareTois Greater than zero.Demo @sharplab.io
As experiment you can set globalization-invariant mode (add
<InvariantGlobalization>true</InvariantGlobalization>entry toPropertyGroupin .csproj) which changes the behaviour - for me result was-32andAis printed beforea.