Search code examples
c#.netgenericsicomparable

Generics and IComparable - error CS00301


I've tried to develop a generic class "MinHeap(T)" implementing IComparable. It works fine when generic is "int" or another class "Code". Going further and using for T a generic class "Node(Code)" leads to the error mentioned below.

I'm probably too new and not understanding subtle differences between IComparable and IComparable(T). Does someone have an idea ? Thanks in advance for your help, LJ

public class MinHeap<T> where T : IComparable
{
...
}
public class Node<T> where T : IComparable
{
    T data
...
    public int CompareTo(object obj)
    {
        Node<T> otherNode = obj as Node<T>;
        return this.data.CompareTo(otherNode.data);
    }
...
}
public class Code : IComparable
{
    public int freq;
...
    public int CompareTo(object obj)
    {
        Code otherCode = obj as Code;
        return this.freq.CompareTo(otherCode.freq);
    }
}
static void Main(string[] args)
{
    MinHeap<int> hInt = new MaxHeap<int>(heapSeed); // works fine
    MinHeap<Code> hCode = new MinHeap<Code>(codeList); // works fine
...
    Node<Code>[] nodeCodeList = new Node<Code>[freqList.Length]; // ok        
    MinHeap<Node<Code>> h = new MinHeap<Node<Code>>(nodeCodeList); // Error
...
}

Error message:

Error 2 The type 'Algorithms.Node(Algorithms.Code)' cannot be used as type parameter 'T' in the generic type or method 'Algorithms.MinHeap(T)'. There is no implicit reference conversion from 'Algorithms.Node(Algorithms.Code)' to 'System.IComparable'.


Solution

  • The class Node<T> does not implement IComparable. It just haves a constraint for the type of T.

    It looks like you've tried to implement the decorator pattern. Implement the interface as well and then map the methods to the decorated object.