Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# let me compile sort code when it doesnt know how to sort

Tags:

c#

sorting

I thought it was odd that C# let me call sort on my class and not specify a way to sort them nor write a compare overload. When i ran this code this error popped up

List<MyClass> myClassArray= new List<MyClass>();
//myClassArray.add(...);
myClassArray.Sort();

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll

Additional information: Failed to compare two elements in the array.

Why does C# let me compile this code when it doesnt know how to sort this! -edit-

Codex ask why it does this. I wrote a theory on why it does it in my comments. Here some example code.

class A : IComparable<A>
{
    public int CompareTo(A a) { return 0; }
}
class C //: IComparable<A>
{
    public int CompareTo(A a) { return 0; }
}
    static void test()
    {
        A a = new A();
        bool b;
        C c = new C();

        object o = a;
        IComparable<A> ia = (IComparable<A>)o;
        b = ia == ia;

        o = c;
        IComparable<A> ic = (IComparable<A>)o;
        b = ic == ic;

        //uncomment this to get a compile time error
        //IComparable<A> ic2 = c;
        return;
    }

If you uncomment the line before return, you'll get a compile time error. When you uncomment IComparable in class c, it will compile and work.


2 Answers

There's no constraint on the generic parameter of List<T> requiring it to implement IComparable<T>. If there were, it would (sort of) guarantee that elements could be sorted, but you wouldn't be able to use List<T> to hold anything that didn't implement IComparable. And since you probably won't be sorting every list you create, this is the right decision.

like image 194
Matt Avatar answered Dec 15 '25 10:12

Matt


Sort should be checking to see if your object implements IComparable. This is a run time check, and since you presumably don't implement it the default comparer doesn't know what to do with your objects, so it throws the exception.

It lets it compile because this isn't a language feature, its a framework feature.

like image 38
i_am_jorf Avatar answered Dec 15 '25 08:12

i_am_jorf



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!