c# - How can I write a single class to compile multiple times with different number types? -
i'm trying write classes handle different number types. know c# (and .net in general, believe) has no inumber
interface, cannot use following:
public class adder<t> t:inumber { public t add(t a, t b) { return + b; } }
that's okay, though, because i'd avoid boxing/unboxing of every 1 of numbers. could, however, use conditional compilation each type want support:
#if float public class adderf { public float add(float a, float b) #else public class adder { public int add(int a, int b) #endif { return + b; } }
this means i'll need compile different library.dll
, libraryf.dll
, however. there more elegant solution this?
obviously, in example, can write code twice. use process, however, create large complicated data structures integer version , floating-point version, not want possibility of copy-paste errors when updating structure. nor want speed loss wrapping floating-point structure in integral-wrapper, , unnecessarily converting inputs more lenient data type.
i guess depends on how strict want be. want add
method takes 2 parameters of exact same type (int , int, float , float) ... ? if not, , performance not super-important, can implement solution decimal
, work.
if have strict, , want specific versions per type, may want t4 code generation. it's akin c++'s templates (some people think c++ templates , c# generics same, they're not).
scott hanselman wrote an interesting article it.
Comments
Post a Comment