Okay so I have a scenario similar to the below code, I have a parent class that implements IComparable and a child class.
class Parent : IComparable<Parent> class Child : Parent Child a = new Child(); Child b = new Child(); a.CompareTo(b);
Now the above works fine, i can compare two of the child objects to each other no problem
List<Child> l = new List<Child>(); l.Add(b); l.Add(a); l.Sort();
The above fails though with an InvalidOperationException. Can someone please explain why this sort isn’t working when the child class does implement the IComparable interface, or at least it seems to me that it does.
Okay here is my CompareTo implementation for my actual parent class
public int CompareTo(IDType other) { return this.Name.ToString().CompareTo(other.ToString()); }
Your type implements
IComparable<Parent>rather thanIComparable<Child>. As the MSDN docs for Sort say, it will throw InvalidOperationException if ‘the default comparer Comparer(T).Default cannot find an implementation of the IComparable(T) generic interface or the IComparable interface for type T.’ And indeed it can’t, where T is Child. If you try making it aList<Parent>you may well find it’s fine.EDIT: Alternatively (and preferably, IMO) implement
IComparable<Child>. At the moment it’s not at all clear that a child can sensibly be compared with another child. ImplementingIComparable<Child>– even if that implementation just defers to the base implementation – advertises the comparability.