The following code is very repetitive:
public static double Interpolate(double x1, double y1, double x2, double y2, double x)
{
return y1 + (x - x1) * (y2 - y1) / (x2 - x1);
}
public static decimal Interpolate(decimal x1, decimal y1, decimal x2, decimal y2, decimal x)
{
return y1 + (x - x1) * (y2 - y1) / (x2 - x1);
}
However, my attempt to use generics does not compile:
public static T Interpolate<T>(T x1, T y1, T x2, T y2, T x)
{
return y1 + (x - x1) * (y2 - y1) / (x2 - x1);
}
The error message is as follows:
Error 2 Operator ‘-‘ cannot be applied to operands of type ‘T’ and ‘T’ C:\Git…\LinearInterpolator.cs
How should I reuse my code?
Edit: fast runtime is important for this modules.
You can’t use operators in generics without specifying a base class constraint on the
T.You might do something like this: Creating a Math library using Generics in C# but personally, unless you really have lots of different formulae then I don’t see much point.
There’s also the possibility of dynamically compiling expression trees for
T, rewriting the types betweendouble/decimalfrom a ‘model’ tree generated by the C# compiler (keeping the arithmetic precedence etc)… if you’re really interested in that I can post the code for such a solution (I’ll need an hour or so though!). Runtime performance will be slower.