I'm trying to write classes which handle different number types. I know that C# (and .Net in general, I believe) has no INumber
interface, so I cannot use something like the following:
public class Adder<T> where T:INumber
{
public T Add(T a, T b)
{
return a + b;
}
}
That's okay, though, because I'd like to avoid the boxing/unboxing of every one of my numbers. I could, however, use conditional compilation for each type I want to 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 a + b;
}
}
This means I'll need to compile a different Library.dll
and LibraryF.dll
, however. Is there any more elegant solution to this?
Obviously, in my example, I can simply write the code twice. I would like to use this process, however, to create large complicated data structures with an integer version and floating-point version, so do not want the possibility of copy-paste errors when updating my structure. Nor do I want the speed loss from wrapping the floating-point structure in an integral-wrapper, and unnecessarily converting all inputs to the more lenient data type.
decimal
s everywhere when I could be usingint
s instead would be effective for that. T4 is definitely a cool technology I didn't know about, and will certainly be looking into it! – Vaientina