There is no general solution for arithmetic operations. But for simple comparisons, you can trivially implement it yourself:
T Min<T>(T x1, T x2) where T:IComparable<T>
{
int comp=x1.CompareTo(x2);
if(comp<=0)
return x1;
else
return x2;
}
But I generally avoid the IComparable<T>
constraint, and rather ask the user to pass in IComparer<T>
as parameter to the constructor, and default to Comparer<T>.Default
if he doesn't specify one.
This technique allows using the class even on types that don't implement IComparable<T>
, provided the user passes in an alternative implementation.
class Foo<T>
{
readonly IComparer<T> _comparer;
public Foo()
:this(Comparer<T>.Default)
{
}
public Foo(IComparer<T> comparer)
{
_comparer=comparer;
}
T Min(T x1, T x2)
{
int comp = _comparer.Compare(x1,x2);
if(comp <= 0)
return x1;
else
return x2;
}
}