jimboweb
jimboweb

Reputation: 4542

Class using generics extending interfaces

So I'm rolling my own max heap and I'm doing something wrong with using a generic class extending an interface. Say I have a class like this:

class SuffixOverlap:IComparable<SuffixOverlap>
{
    //other code for the class
     public int CompareTo(SuffixOverlap other)
    {
        return SomeProperty.CompareTo(other.SomeProperty);
    }
}

And then I create my heap class:

class LiteHeap<T> where T:IComparable
{
    T[] HeapArray;
    int HeapSize = 0;
    public LiteHeap(List<T> vals)
    {
        HeapArray = new T[vals.Count()];
        foreach(var val in vals)
        {
            insert(val);
        }
    }

    //the usual max heap methods
}

But when I try to do this:

LiteHeap<SuffixOverlap> olHeap = new LiteHeap<SuffixOverlap>(listOfSuffixOverlaps);

I get the error: The type SuffixOverlap cannot be used as a type parameter T in the generic type or method LiteHeap<T>. There is no implicit reference conversion from SuffixOverlap to System.IComparable.

How do I create LiteHeap as a class that uses generic class T implementing IComparable so I can write new LiteHeap<SomeClass> and it will work where SomeClass implements IComparable

Upvotes: 0

Views: 2356

Answers (1)

SLaks
SLaks

Reputation: 887235

IComparable and IComparable<T> are different, completely-unrelated interfaces.

You need to change that to where T : IComparable<T>, so that it actually matches your class.

Upvotes: 5

Related Questions