I wonder if with Generic Constraint (when) it is possible to allow this code ?
And what is the right pattern to do this?
public MyClass<T>
{
public void MyMethod(T a, T b)
{
//some code
var result = a<b;
//some code
}
}
my question is for all operator in general
+, -, !, ~, ++, --, *, /, %, &, |, ^, <<, >>, ==, !=, <, >, <=, >=
At this point of time (May 2018), the only thing you can do is add a constraint to
IComparable<T>
to the class definition and use theCompareTo
method instead of the<
.This will cover
<
,<=
,>
,>=
(and technically even the==
, but it is better to useIEquatable<T>
), for the==
you can add a constraint toIEquatable<T>
to the class definition and use theEquals
method instead of the==
(and the!Equals
instead of the!=
).For math/bitwise operators at this point there is no hope. There are always requests for this feature in the C# wishlist, but they always get postponed. In the C# 8.0 this feature won't be present (probably). See the official list of candidates. See Generic C# Code and the Plus Operator for an older question about this. Note that the solutions given won't give errors at compile time if you try to use a non-existing operator, but will give those errors at runtime.