One workaround with decent performance (that's still ugly) is using a struct that encapsulates the arithmetic behavior you want.
You first define an interface:
public interface IArithmetic
{
T Add(T n1,T n2);
}
Then you implement that interface using a struct
:
public struct DoubleArithmetic:IArithmetic
{
public double Add(double n1,double n2)
{
return n1+n2;
}
}
And finally you pass the struct as generic parameter into your type:
public class Matrix
where TArithmetic:struct, IArithmetic
{
private static readonly TArithmetic arithmetic=new TArithmetic();
void DoStuff()
{
arithmetic.Add(1,2);
}
}
I haven't benchmarked it, but I suspect it's rather fast since generics get specialized for each value type passed into it. That's why DoubleArithmetic
is a struct
.