In C# 4.0, whenever I compare two strings which have one or more trailing slashes, the comparison gives incorrect results:
String a = "1/2.1/";
String b = "1/2/";
if (a.CompareTo(b) > 0)
MessageBox.Show("Correct: " + a + " > " + b);
else
MessageBox.Show("Not correct: " + a + " <= " + b);
a = a.TrimEnd('/');
b = b.TrimEnd('/');
if (a.CompareTo(b) > 0)
MessageBox.Show("Trailing slash removed. Correct: " + a + " > " + b);
else
MessageBox.Show("Trailing slash removed. Not correct: " + a + " <= " + b);
Lexically speaking, "1/2.1/" comes after "1/2/", and there is not much question about that.
This behaviour also occurs in other places, such as sorting a datatable using the Select method.
Am I doing something wrong? Or is this a bug in .Net? It should not even have anything to do with culture-specific information etc. since a slash is part of the most basic US ASCII character set.
I am running into this when comparing SQL Server hierarchyIDs. It's easy enough to solve but it is a somewhat astonishing problem.