Search code examples
c#genericsgeneric-list

Comparing Elements of a Generic List


I have a TestClass<T> that will evolve to a heap-based priority queue. The heap is List<T> type.

I was working on reordering code and I needed to compare the elements of the List<T>. As you can guess I received error CS0019: Operator < cannot be applied to operands of type T and T.

I KNOW this is not surprising and C# generics are not C++ templates. So, I tried to constrain the Type T with an IComparable. But it did not help as well.

The suggestions I found (in order to solve this problem) were mostly creating a dummy class that defines such operators and constrain the T with this class. However, I did not find this solution very convenient.

So, are there any other ways to solve this?

Here's the related piece of code:

using System;
using System.Collections.Generic;

public class TestClass<T>
    where T : IComparable
{
    private List<T> heap;

    public TestClass(int maxSize)
    {
        this.heap = new List<T>(maxSize + 1);
    }

    private void ReorderUpwards(int nodeIndex)
    {
        while (nodeIndex > 1 && this.heap[nodeIndex / 2] < this.heap[nodeIndex])
        {
            nodeIndex /= 2;
        }
    }
}

Solution

  • Use IComparable and instead of using > and < use CompareTo method

    value.CompareTo(value2) <= 0