Following code won't compile:
class Test<T> where T : class, IComparable
{
public bool IsGreater(T t1, T t2)
{
return t1 > t2; // Cannot apply operator '>' to operands of type 'T' and 'T'
}
}
How I can make it work? I want it to work for T = int, double, DateTime, etc.
The IComparable interface that you have used here as the type constraint gives you a CompareTo method. So you can do something like this:
public bool IsGreater(T t1, T t2)
{
return t1.CompareTo(t2) > 0;
}
While currently you can't do exactly that (and you need to use solution by @DavidG) there is a preview feature you can enable called generic math which is based on static abstract interface members and ships with interface specially for that purpose:
[RequiresPreviewFeatures]
public interface IComparisonOperators<TSelf, TOther> : IComparable, IComparable<TOther>, IEqualityOperators<TSelf, TOther>, IEquatable<TOther> where TSelf : IComparisonOperators<TSelf, TOther>
{
static bool operator <(TSelf left, TOther right);
static bool operator <=(TSelf left, TOther right);
static bool operator >(TSelf left, TOther right);
static bool operator >=(TSelf left, TOther right);
}
So in future (or right now if you want to be an early adopter) you will be able to do (if no major overhaul comes for this preview):
class Test<T> where T : IComparisonOperators<T, T>
{
public bool IsGreater(T t1, T t2)
{
return t1 > t2;
}
}
Note that for Test to support int, double, DateTime, etc. you need to remove class constraint (with or without this preview feature).
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