Object type does not implement IComparable

662 Views Asked by At

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?

1

There are 1 best solutions below

2
CaveCoder On BEST ANSWER

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>();