Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 405
DynamicScope Avatar asked Oct 19 '25 02:10

DynamicScope


1 Answers

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;
}
like image 141
PraveenVenu Avatar answered Oct 20 '25 17:10

PraveenVenu