Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to temporarily replace one primitive type with another when compiling to different targets?

How to easily/quickly replace float's for doubles (for example) for compiling to two different targets using these two particular choices of primitive types?

Discussion: I have a large amount of c# code under development that I need to compile to alternatively use float, double or decimals depending on the use case of the target assembly.

Using something like “class MYNumber : Double” so that it is only necessary to change one line of code does not work as Double is sealed, and obviously there is no #define in C#. Peppering the code with #if #else statements is also not an option, there is just too much supporting Math operators/related code using these particular primitive types.

I am at a loss on how to do this apparently simple task, thanks!

Edit: Just a quick comment in relation to boxing mentioned in Kyles reply: Unfortunately I need to avoid boxing, mainly since float's are being chosen when maximum speed is required, and decimals when maximum accuracy is the priority (and taking the 20x+ performance hit is acceptable). Boxing would probably rules out decimals as a valid choice and defeat the purpose somewhat.

Edit2: For reference, those suggesting generics as a possible answer to this question note that there are many issues which count generics out (at least for our needs). For an overview and further references see Using generics for calculations

like image 412
Keith Avatar asked Aug 26 '09 16:08

Keith


1 Answers

The best way to do this would be using #if as Andrew stated above. However, an interesting idea to think about would be something like this:

#if USE_FLOAT
using Numeric = System.Single;
#endif

#if USE_DOUBLE
using Numeric = System.Double;
#endif

#if USE_DECIMAL
using Numeric = System.Decimal;
#endif

public class SomeClass
{
    public Numeric MyValue{get;set;}
}

EDIT:

I still really like this solution, it allows you to do some other really cool things such as:

Numeric.Parse();
Numeric.TryParse();

Which will work for all three types

like image 71
LorenVS Avatar answered Sep 21 '22 03:09

LorenVS