Nick Nick - 4 months ago 8
C# Question

C# String: why string a == b operator gives different answer than a.CompareTo(b) == 0?

I messed with C# a little and found a code that gives very uncomfortable results:

static void Main(string[] args)
{
string a = "string", b = "string\0";
bool b1 = a == b;
bool b2 = (a.CompareTo(b) > 0);
bool b3 = (a.CompareTo(b) < 0);
bool b4 = (a.CompareTo(b) == 0);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine("{0} {1} {2} {3}", b1, b2, b3, b4);
}


Output:

string
string
False False False True


Expected output (on of the):

string
string
True False False True

Answer

The result of CompareTo doesn't imply equality, it relates to sort order. I'm not sure it's too surprising that the null character is ignored for sorting purposes.

Per the documentation:

Character sets include ignorable characters. The CompareTo(String) method does not consider such characters when it performs a culture-sensitive comparison.

Comments