c# - Why can I not use IComparable<T> on ancestor class and compare child classes? -


i'm trying sort list of objects using list.sort(), @ runtime tells me cannot compare elements in array.

failed compare 2 elements in array

class structure:

public abstract class parent : icomparable<parent> {     public string title;     public parent(string title){this.title = title;}      public int compareto(parent other){         return this.title.compareto(other.title);     } }  public class child : parent {     public child(string title):base(title){} }  list<child> children = getchildren(); children.sort(); //fails "failed compare 2 elements in array." 

why can not compare subclasses of base implements icomparable<t>? i'm missing something, cannot see why should not allowed.

edit: should clarify i'm targeting .net 3.5 (sharepoint 2010)

edit2: .net 3.5 problem (see answer below).

i assume .net version before .net 4.0; after .net 4.0 icomparable<in t>, , should work ok in many cases - requires variance changes in 4.0

the list list<child> - sorting try use either icomparable<child> or icomparable - neither of implemented. implement icomparable @ parent level, perhaps:

public abstract class parent : icomparable<parent>, icomparable {     public string title;     public parent(string title){this.title = title;}      int icomparable.compareto(object other) {         return compareto((parent)other);     }     public int compareto(parent other){         return this.title.compareto(other.title);     } } 

which apply same logic via object.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -