Problem with generic

  • Thread starter Thread starter Torben Laursen
  • Start date Start date
T

Torben Laursen

I have a class that is generic and can only be used with numerical types
like double or decimals

A example code is:
class<NumType>
{
public NumType Test(NumType Val)
{
NumType d = 0.0; //The problem is this line. This will not compile with the
error: Cannot convert type double to NumType
return Val + d;
}
}
Can anyone show me how to rewrite the code to it will compile?
For example is there a way of forcing the NumType to only be numerical
types?

Thanks Torben
 
You can't (sadly) use the operators (such as arithmetic) with
generics.

It is a bit of a pain, and gets noted often ;-p

To re-write it so that it will compile? Use method overloads (one per
numeric type you need to support), not generics. Sorry ;-(

Marc
 
Torben said:
NumType d = 0.0; //The problem is this line. This will not compile with the

NumType d = default(NumType);

But you'll probably have trouble with the Val + d line too. I don't
believe there is a way to say that the generic type is numeric and
therefore has basic mathematical operators defined for it.

I think this is just a limitation of the current implementation of generics.

Cheers

Russell
 
Note; my "look-ahead" had already jumped to the + line; Clive is of
course right about using "default(T)" to get a zero.

Marc
 
Back
Top