Generics and IComparable Implementation

I'm very new to generics, and I'm trying to write a simple class that will be generic, but also allows you to sort some description in a member variable of a string.

At the moment I have a base class, but when I try to implement a member of the CompareTo () interface, I get an error message saying that it is not implemented. What is the problem?

using System; namespace GenericsPracticeConsole.Types { class SortableGenericType<T> : IComparable { private T t; private string stringName; public T name { get { return t; } set { t = value; } } public int CompareTo(SortableGenericType<T> ourObject) { return stringName.CompareTo(ourObject.stringName); } } } 
+6
source share
2 answers

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 } } } 
+7
source

IComparable defines a public int CompareTo(object obj) method. Pay attention to the type of the parameter - it object , not your own type. That is why you are not really implementing an interface.

What you need to do is implement IComparable<SortableGenericType<T>>

+5
source

Source: https://habr.com/ru/post/907383/


All Articles