Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: generic math functions (Min, Max etc.)

Tags:

c#

math

I was thinking about writing generic functions for basic Math operations such as Min, Max etc. But i i dont know how to compare two generic types :

public T Max<T>(T v1, T v2) where T: struct
{
   return (v1 > v2 ? v1 : v2);
}

How about that?

Thank you.

like image 525
Feryt Avatar asked Dec 15 '09 10:12

Feryt


2 Answers

You probably want to constrain the generic types to implement IComparable:

public T Max<T>(T v1, T v2) where T: struct, IComparable<T>

and then use the CompareTo method:

{
    return (v1.CompareTo(v2) > 0 ? v1 : v2);
}
like image 121
Joey Avatar answered Nov 17 '22 03:11

Joey


If you only want to create comparison functions then you could use the default comparer for the type T. For example:

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

If T implements IComparable<T> then that comparer will be used; if T doesn't implement IComparable<T> but does implement IComparable then that comparer will be used; if T doesn't implement either IComparable<T> or IComparable then a runtime exception will be thrown.

If you want/need to do more than just compare the items then you could have a look at the generic operators implementation in MiscUtil and the related article.

like image 25
LukeH Avatar answered Nov 17 '22 04:11

LukeH