I have a method as follows:
int coerce(int val, int min=0, int max = 10)
{
if (val < min)
return min;
if (val > max)
return max;
return val;
}
Now, I have to make it for byte
, float
, double
, and other numeric types.
As all we know, making numerous similar methods for those types is very ineffective, so I want to make it into a generic method. The following is the what I tried to do:
T coerce<T>(T val, T min=(T)0, T max=(T)10) where T:IComparable
{
// ... same as the above ...
}
I know that the code does not run, and that's why I'm asking for this. I'm currently confused by two questions:
How can I compare
T
types?Visual Studio warns about the operator
<
and>
. I tried to usewhere T:IComparable
but it did not solve my problem.How can I set default values for a generic argument?
I tried to use
(T)0
and(T)10
for it. But it was not a good choice, anyway.
It may be a simple question, but I couldn't find answer from Google.