Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use generics to develop code that works for doubles and decimals

Tags:

c#

c#-4.0

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.

like image 778
Arne Lund Avatar asked Apr 24 '12 15:04

Arne Lund


1 Answers

Your current code is fine as it is - possibly the best you can achieve without casting doubles to decimals.

A generic solution is possible, but would involve quite a lot of infrastructure - so much so that it would make things way too complex.

like image 199
Oded Avatar answered Nov 06 '22 04:11

Oded