Vitalii Nesterenko
Vitalii Nesterenko

Reputation: 45

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?

Upvotes: 0

Views: 990

Answers (1)

CaveCoder
CaveCoder

Reputation: 791

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

Upvotes: 1

Related Questions