Search code examples
c#icomparablegenerics

How to use a generic class for System.Math methods in C#


I am trying to achieve something similar to the following code snippet.

enter image description here

As the red line indicates Math.Min for IComparable<T> does not seem to work. I need to use Math.Min or Math.Max for this generic class. The T is going to be either int or double or decimal type.

How could I easily solve this?


Solution

  • Write your own generic Max and Min

    public static T Max<T>(T x, T y)
    {
        return (Comparer<T>.Default.Compare(x, y) > 0) ? x : y;
    }