I’m trying to write an extension method on numeric types to be used in a fluent testing framework I’m building. Basically, I want to do this:
public static ShouldBeGreaterThan<T>(this T actual, T expected, string message)
where T : int || T: double || etc...
Just where T : struct doesn’t do, since that will also match string and bool, and possibly something else I’m forgetting. is there something I can do to match only numeric types? (Specifically types that implement the > and < operators, so I can compare them… If this means I’m matching dates as well, it doesn’t really matter – the extension will still do what I expect.)
In this case you want to constrain your generic to the
IComparableinterface, which gives you access to theCompareTomethod, since this interface allows you to answer the questionShouldBeGreaterThan.Numeric types will implement that interface and the fact that it also works on strings shouldn’t bother you that much.
Edit:
My comment from 2020 is not true anymore!
Since .NET 7 you could also consider constraining to the
INumber<TSelf>– incidentally, the interface inherits fromIComparablebut would then indeed exclude e.g. thestringtype. Additionally, though, the interface also inherits from theIComparisonOperatorsinterface, which will give you all the operators you’d expect (<, <=, >=, >, ==, !=)