Nick Nick - 1 year ago 80
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("{0} {1} {2} {3}", b1, b2, b3, b4);


False False False True

Expected output (on of the):

True False False True

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download