I am very new to generics and I am trying to write a simple class which will be generic but also allow sorting of some description on a string member variable.
At the moment I have a basic class but when I try to implement the interface member CompareTo() I get an error at the top telling me it is not implemented. What is the issue here?
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);
}
}
}
There are two interfaces
IComparableandIComparable<U>.IComparableis the older one (that came before generics) which requires instances to be compared with arbitrary objects.IComparable<U>requires instances to be compared with instances ofU. If you want to declare that you will compare instances of SortableGenericType on stringName fields this is what you should do:If you also want to implement IComparable:
If your class was a collection that is going to hold items of type
Tand you needed those items to be orderable (this is not what you ask but it is the most common scenario) than you would requireTto beIComparable<T>: