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.
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.