Sorry if the title is poorly worded. Let's say I have a ray tracer and I want there to be the ability to use either floats or doubles. How can I make it possible to declare a new instance of the class choosing either floats or doubles? I don't want to create two classes and call one double and the other single.
There is not a clean way to handle this in .NET. Generics do not support arithmetic operations directly. You can solve this via workarounds such as MiscUtils or via the creation of a separate calculator class and delegating the math to it, but this often makes the code more complex than having two implementations.
You could use dynamic
here internally, which would work as well. However, this will add a (slight) overhead, which may mitigate the usefulness of this. If performance is the main reason you don't want to only support double-precision math, then using dynamic is probably not an option.
One option would be to use T4 to create a template that builds both versions of the code from a single source file. This would provide you full, native support without overhead (it's essentially just writing the two classes for you).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With