Possible Duplicate:
Define a generic that implements the + operator
I am recently working on a C# class library implementing an algorithm. The point is that I would like the users of the library to be able to choose the machine precision (single or double) the algorithm should operate with, and I'm trying to do it with generics. So, for instance:
Algorithm<double> a = new Algorithm<double>();
/** Some initializations here */
double result = a.Solve();
or
Algorithm<float> a = new Algorithm<float>();
/** Some initializations here */
float result = a.Solve();
Thus, the type parameter for the generic classes is meant to be a decimal number (because in the algorithm code I need to use +, *, /, -), but I don't know which kind of type constraint to impose on it. I have thought about building an interface with all the operators but, unfortunately, this is not allowed. Any ideas?
Otherwise, is it possible to obtain in C# something similar to template specialization in C++?
Thank you
Tommaso
It's possible to add Freon to your air conditioner unit yourself, but you'll need some general knowledge about ACs and a few specific tools to do it correctly. The process can be dangerous, so hire a qualified professional if you feel unsure about what to do.
According to Home Advisor, the average cost for a Freon refill (in 2021) is between $100 and $350. However, prices continue to go up. If you have an older, larger R-22 system, it can cost $600 or more to refill.
You can't, basically. The CLR type system doesn't support that kind of constraint.
I've previous blogged about how we could describe such constraints using "static interfaces" but I don't know of any plans to do anything similar.
You might want to look at the MiscUtil generic operator support which would let you use the operators - but you'd have to use a constraint of just struct
or something like that, which would of course allow things like Guid
which you don't want.
The closest match is value type constrain.
C# allows only three types of constrains
For complete documentation refer MSDN:
http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx#csharp_generics_topic4
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