3

I was trying to debug a problem and ran into this issue. Maybe somebody can explain it to me. This is the code in question

public int Compare(CustomClass rt1, CustomClass rt2)
{
     if (rt1 == null & rt2 == null)
                return 0;
     if (rt1 == null)
                return -1;
     if (rt2 == null)
                return 1;
     if (rt1.yPos < rt2.yPos)
                return -1;
     if (rt1.yPos == rt2.yPos)
     {
                if (rt1.xPos < rt2.xPos)
                    return -1;
                if (rt1.xPos == rt2.xPos)
                    return 0;
     }
     return 1;
}

The error I was getting was: IComparer (or the IComparable methods it relies upon) did not return zero when Array.Sort called x. CompareTo(x).

To make it even more interesting, the error would not occur if I ran it from VS in debug mode. Only if I put it in release mode AND hit "start without debugging". Anybody have any ideas why this would happen? I fixed the problem by adding an "if(rt1 == rt2) return 0;" line to the beginning of the function, but would really like to know what is going on.

Extra info: Yes, this implements the IComparer class

Kevin
  • 7,162
  • 11
  • 46
  • 70

2 Answers2

2

your missing an amperstand (&) (is this a typo?)

if (rt1 == null & rt2 == null) // oops!
if (rt1 == null && rt2 == null) // like this....
Steven Sudit
  • 19,391
  • 1
  • 51
  • 53
Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
0

Sometimes a sort algorithm will end up comparing an object to itself. When this happened, it triggered the code:

if (rt1 == null)
    return -1;

It was this that caused the error. You've got to be sure that you have all cases covered.

And if those x,y values represent points, you might want to check this article on sorting them: http://www.c-sharpcorner.com/UploadFile/mgold/SortedDictionarySample06202007142815PM/SortedDictionarySample.aspx

Michael Dillon
  • 31,973
  • 6
  • 70
  • 106