C# BinarySearch breaks when inheriting from something that implements IComparable<T>?

Posted by Ender on Stack Overflow See other posts from Stack Overflow or by Ender
Published on 2010-05-02T04:45:17Z Indexed on 2010/05/02 4:47 UTC
Read the original article Hit count: 286

Filed under:
|
|
|
|

In .NET the BinarySearch algorithm (in Lists, Arrays, etc.) appears to fail if the items you are trying to search inherit from an IComparable instead of implementing it directly:

List<B> foo = new List<B>(); // B inherits from A, which implements IComparable<A>
foo.Add(new B());
foo.BinarySearch(new B());   // InvalidOperationException, "Failed to compare two elements in the array."

Where:

public abstract class A : IComparable<A>
{
    public int x;

    public int CompareTo(A other)
    {
        return x.CompareTo(other.x);
    }
}

public class B : A {}

Is there a way around this? Implementing CompareTo(B other) in class B doesn't seem to work.

© Stack Overflow or respective owner

Related posts about c#

Related posts about sorting