-2

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;
        }
    }
}
ciyo
  • 725
  • 4
  • 16
  • 36
  • 2
    No, the question [you deleted](https://stackoverflow.com/questions/49858413/comparing-elements-of-a-generic-list?noredirect=1) was duped to another that **is not Python**, look again. – DavidG Apr 16 '18 at 13:37
  • More convenient than using IComparable and providing a method that actually does the comparison you want made? You need to look at this a little harder. –  Apr 16 '18 at 13:39
  • @DavidG then could please tell me that if this is a duplicate of the question you suggest, how come "value.CompareTo(_minimumValue) >= 0" is not solving the problem? – ciyo Apr 16 '18 at 13:40
  • That literally **is** the solution, now apply it to your code. – DavidG Apr 16 '18 at 13:41
  • @DavidG and there is literally no other ways to do it without using this method? – ciyo Apr 16 '18 at 13:47
  • Well what more do you need? What is the issue with doing it this way? – DavidG Apr 16 '18 at 13:48
  • @DavidG I just wonder – ciyo Apr 16 '18 at 13:51

1 Answers1

1

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

value.CompareTo(value2) <= 0
MistyK
  • 6,055
  • 2
  • 42
  • 76