Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this Custom Compare function

Tags:

c#

icomparer

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

like image 534
Kevin Avatar asked Dec 30 '25 15:12

Kevin


1 Answers

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

if (rt1 == null & rt2 == null) // oops!
if (rt1 == null && rt2 == null) // like this....
like image 80
Muad'Dib Avatar answered Jan 01 '26 04:01

Muad'Dib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!