Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I allow a class to be declared to use either floats or doubles?

Tags:

c#

types

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.

like image 868
Levi H Avatar asked Dec 12 '12 23:12

Levi H


1 Answers

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).

like image 152
Reed Copsey Avatar answered Oct 13 '22 10:10

Reed Copsey