There are two interfaces, IComparable
and IComparable<U>
. IComparable
is an older one (which appeared before generics) that requires instances to be compared with arbitrary objects. IComparable<U>
requires instances to be compared with instances of U
If you want to declare that you are comparing SortableGenericType instances in stringName fields, this is what you should do:
class SortableGenericType<T> : IComparable<SortableGenericType<T>> { // }
If you also want to implement IComparable:
class SortableGenericType<T> : IComparable, IComparable<SortableGenericType<T>> { private string stringName; public T name { get; set; } public int CompareTo(SortableGenericType<T> ourObject) { //I forgot to add this statement: if(ourObject == null) return -1; return stringName.CompareTo(ourObject.stringName); } public int CompareTo(object obj) { if (obj.GetType() != GetType()) return -1; return CompareTo(obj as SortableGenericType<T>); } }
If your class is a collection that will contain elements of type T
, and you need these elements for ordering (this is not what you ask for, but this is the most common scenario) than you need T
IComparable<T>
:
class SomeCollection<T> where T : IComparable<T> { private List<T> items; private void Sort() { // T item1; T item2; if(item1.CompareTo(item2) < 0) { //bla bla } } }
source share