I have a generic class that takes a type T
. Within this class I have a method were I need to compare a type T
to another type T
such as:
public class MyClass<T>
{
public T MaxValue
{
// Implimentation for MaxValue
}
public T MyMethod(T argument)
{
if(argument > this.MaxValue)
{
// Then do something
}
}
}
The comparison operation inside of MyMethod
fails with Compiler Error CS0019. Is it possible to add a constraint to T
to make this work? I tried adding a where T: IComparable<T>
to the class definition to no avail.
Comparison operators are binary operators that test a condition and return 1 if that condition is logically true and 0 if that condition is false . The relational operator expressions have the form
the values of the operands after conversion are compared in the usual mathematical sense (except that positive and negative zeroes compare equal and any comparison involving a NaN value returns zero) Note that complex and imaginary numbers cannot be compared with these operators.
if both operands have arithmetic types, usual arithmetic conversions are performed and the resulting values are compared in the usual mathematical sense (except that positive and negative zeroes compare equal and any comparison involving a NaN value, including equality with itself, returns zero).
The equality operator expressions have the form The type of any equality operator expression is int, and its value (which is not an lvalue) is 1 when the specified relationship holds true and 0 when the specified relationship does not hold.
Adding constraint to make sure that the type implements IComparable<T>
is a way to go. However, you cannot use the <
operator - the interface provides a method CompareTo
to do the same thing:
public class MyClass<T> where T : IComparable<T> {
public T MaxValue {
// Implimentation for MaxValue
}
public T MyMethod(T argument) {
if(argument.CompareTo(this.MaxValue) > 0){
// Then do something
}
}
}
If you needed other numeric operators than just comparison, the situation is more difficult, because you cannot add constraint to support for example +
operator and there is no corresponding interface. Some ideas about this can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With