0

How can I compare two nullable numbers of any type (int, decimal, float) and return a great of two

I tried this but it only works for integers

public static int? Compare(int? value1, int? value2)
{
    if(value1> value2)
    return value1;

    return value2;
}

I tried this, but you cannot use > operator on operands of type T.

public static Compare<T>(T value1, T value2)
{
    if(value1> value2)
    return value1;

    return value2;
}

Any ideas?

gunr2171
  • 16,104
  • 25
  • 61
  • 88
mko
  • 6,638
  • 12
  • 67
  • 118
  • 1
    Your generic argument `T` is wide open. It allows _any_ type. If `T` is a string, how would use figure out "the greater option"? You need to clamp it down to a datatype using `IComparable`. – gunr2171 Jul 05 '19 at 20:17
  • See https://stackoverflow.com/questions/32664/is-there-a-constraint-that-restricts-my-generic-method-to-numeric-types – gunr2171 Jul 05 '19 at 20:19
  • Assuming you are not looking for something like `Compare(int? value1, float? value2)` then standard duplicate for *any* types that are comparable including numeric once (https://stackoverflow.com/questions/6480577/how-to-compare-values-of-generic-types) is one you are looking for. If you need to compare different types that would be way more interesting - [edit] if it is the case. – Alexei Levenkov Jul 05 '19 at 20:26

1 Answers1

2

You can only use the > operator with numbers. For a more generic approach (e.g., if you also want to use the method for strings), you can use the IComparable interface:

public static T Compare<T> (T value1, T value2) where T : IComparable<T>
{
    if (value1.CompareTo(value2) > 0)
        return value1;

    return value2;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I would include null checks and use IComparable instead, although this last one is debatable. –  Jul 05 '19 at 20:25