Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to impose, in a C# generic type parameter, that some operators are supported? [duplicate]

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

like image 562
tunnuz Avatar asked Sep 06 '10 14:09

tunnuz


People also ask

Can I add Freon to my AC unit myself?

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.

How much does it cost to put Freon in AC unit?

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.


2 Answers

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.

like image 82
Jon Skeet Avatar answered Oct 19 '22 15:10

Jon Skeet


The closest match is value type constrain.

C# allows only three types of constrains

  1. Derivation Constrain
  2. Constructor
  3. Reference/Value type.

For complete documentation refer MSDN:
http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx#csharp_generics_topic4

like image 21
Guru Avatar answered Oct 19 '22 14:10

Guru