Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A Scary Bug in String.Compare, ArrayList.Sort, SortedList etc

0.00/5 (No votes)
13 Nov 2006 1  
A Scary Bug in String.Compare, ArrayList.Sort, SortedList etc

Introduction

I found this scary bug working with the SortedList. Certain keys I added could not be retrieved again. Investigation proved the problem extended to ArrayList.Sort and then to String.Compare.

It is possible to create three strings s1, s2, s3 so that String.Compare reports s1 > s2 and s2 > s3 and s3 > s1. Ie the string operation is not transitive.

This bug occurs, I believe, because of special logic in the string compare function to sort words like "coop" and co-op" together. However when two hyphens are used in a string the logic can fail. If you use two hyphens compare with String.CompareOrdinal until this problem is fixed.

Many thanks to Marc Gravell and others who helped identify the problem.

This problem has been reported to Microsoft at the link below. Please feel free to vote for it!

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=236900&wa=wsignin1.0

SourceCode:

// A c# Console Application 

using System; 
 
class Class1
{ 
    [STAThread]
    static void Main(string[] args)
    {
        string s1,s2,s3;

        s1 = "-0.67:-0.33:0.33"; 
        s2 = "0.67:-0.33:0.33"; 
        s3 = "-0.67:0.33:-0.33"; 
        Console.WriteLine( "String.Compare:" );
        Console.WriteLine( CompareTwoStrings(s1,s2,0) );
        Console.WriteLine( CompareTwoStrings(s2,s3,0) );
        Console.WriteLine( CompareTwoStrings(s3,s1,0) ); 
        Console.WriteLine();
        Console.WriteLine( "CompareOrdinal:" );
        Console.WriteLine( CompareTwoStrings(s1,s2,1) );
        Console.WriteLine( CompareTwoStrings(s2,s3,1) );
        Console.WriteLine(CompareTwoStrings(s3,s1,1) ); 
        Console.ReadLine(); 
    } 
    static string CompareTwoStrings( string s1, string s2, int mode)
    {
        int i;
        if (mode==0)
            i=String.Compare(s1,s2);
        else if (mode==1)
            i=String.CompareOrdinal(s1,s2);
        else
            return null;
        if (i<0) return s1 + " is less than " + s2;
        if (i>0) return s1 + " is greater than " + s2;
        return s1 + " is equal to " + s2;
    }
} 

Output:

String.Compare:
-0.67:-0.33:0.33 is greater than 0.67:-0.33:0.33
0.67:-0.33:0.33 is greater than -0.67:0.33:-0.33
-0.67:0.33:-0.33 is greater than -0.67:-0.33:0.33

CompareOrdinal:
-0.67:-0.33:0.33 is less than 0.67:-0.33:0.33
0.67:-0.33:0.33 is greater than -0.67:0.33:-0.33
-0.67:0.33:-0.33 is greater than -0.67:-0.33:0.33

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here