Reputation: 333
I tried using IComparable<T>
in a generic class to compare elements of type T and I get the following error:
"Operator '<' cannot be applied to operands of type 'T' and 'T'"
I was wondering if there could be a work around that.
Here is a simple example that IComparable<T>
is working when I define my class to take int:
public class IntStack : IComparable<IntStack>
{
public int[] stack = new int[2];
public int CompareTo(IntStack other)
{
// If the current stack < other stack return -1
// If the current stack > other stack return +1
// If current stack entries == other stack entries return 0
for (var current = 0; current < 2; current++)
{
if (stack[current] < other.stack[current])
{
return -1;
}
else if (stack[current] > other.stack[current])
{
return 1;
}
}
return 0;
}
}
IComparable<T>
is now not working here when I change the class above to take generic:
public class Mystack<T> : IComparable<Mystack<T>> where T : IComparable
{
public T[] stack = new T[2];
public int CompareTo(Mystack<T> other)
{
// If the current stack < other stack return -1
// If the current stack > other stack return +1
// If current stack entries == other stack entries return 0
for (var current = 0; current < 2; current++)
{
if (stack[current] < other.stack[current])
{
return -1;
}
else if (stack[current] > other.stack[current])
{
return 1;
}
}
return 0;
}
Upvotes: 2
Views: 463
Reputation: 1
better one can use operator overloading for
!= These are the operators for comparison when using numeric expression, but if you want to compare object of some sort or some structure then the best option is to overload these 4 operators defined above.
Best way would to instead of using .CompareTo method everytime in a method, use the above 4 after defining overloaded operators
Upvotes: -1
Reputation: 632
The reason why you are getting this error is that you cannot use inequality operators ("<", ">") with IComparable, unless you override them.
You can use CompareTo() instead.
public class Mystack<T> : IComparable<Mystack<T>> where T : IComparable
{
public T[] stack = new T[2];
public int CompareTo(Mystack<T> other)
{
// If the current stack < other stack return -1
// If the current stack > other stack return +1
// If current stack entries == other stack entries return 0
for (var current = 0; current < 2; current++)
{
if (stack[current].CompareTo(other.stack[current]) < 0)
{
return -1;
}
else if (stack[current].CompareTo(other.stack[current]) > 0)
{
return 1;
}
}
return 0;
}
Upvotes: 2