Search code examples
c#automated-refactoring

Double and Float coexisting implementation


I have a very large (and old and ugly structured, ported from Fortran to C#) mathematical library, where all calculations are now done using doubles (as there were inaccuracies). However, to compare the results with the results from the old implementation, we sometimes have to switch back to floats - to check that the ported code is correct.

My idea would be to somehow generate a second library from the first one, where all variables and called methods are replaced by the corresponding float implementation. Is there any automatic solution to allow switching between floats and doubles without manually implementing all the code twice? I am talking about more than 30000 lines of code.


Solution

  • Code generation is probably your best option - using the same source codes twice, but replacing all float operations with double with some global replace in the other set automatically.

    If you want to keep to pure C# source codes, you could abuse the using directive. Have two separate projects - one for float, another for double. Have both of them use the same source code files (one will have them physically, the other will only have links). One of the projects will have a conditional compilation constant FLOAT. Instead of using float or double in your source code, you will use e.g. Number, defined as

    #if FLOAT
    using Number = float;
    #else
    using Number = double;
    #endif
    

    The proper type for Number will be substituted at compile-time, so everything like type inference etc. works properly. Visual Studio 2015 will even warn you if there's issues in the source that only impact one of the projects using the same linked source code file.