Search code examples
c#objectcompareicomparable

Object type does not implement IComparable


I've got a LinkedList class, where every node has a data and their data are generic type T

public class LinkedList<T> where T : IComparable
{
}

In its methods I compare data of nodes, but as we know, object type doesn't implement IComparable,

LinkedList <int> listTest = new LinkedList<int>(); //it's OK
LinkedList <object> listTest2 = new LinkedList<object>(); //it doesn't work

but how can I compare all types that could be instead of T?


Solution

  • You cant use the object type because it does not implement IComparable and break Generic Constraint.

    You need to create a new object that implements the IComparable interface.

    public class Foo : IComparable {
    }
    
    var list = new LinkedList<Foo>();