Search code examples
c#genericsnumeric

Generic constraint to match numeric types


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.)


Solution

  • In this case you want to constrain your generic to the IComparable interface, which gives you access to the CompareTo method, since this interface allows you to answer the question ShouldBeGreaterThan.

    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 from IComparable but would then indeed exclude e.g. the string type. Additionally, though, the interface also inherits from the IComparisonOperators interface, which will give you all the operators you'd expect (<, <=, >=, >, ==, !=)