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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With