Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I constrain a generic parameter to implement basic math operators?

Tags:

.net

vb.net

Is there a way you can do this ?

I would like to have a collection class of T that would be able to do addition, substraction on the T type. I would like to keep T generic instead of having couple collections with the same code, but different types.

How would you constrain the generic T ?

Example: I would like to define a Collection(of T as IDoMaths). I wouldn't like to create my own integer etc classes with named methods to do the operations, because I think it would be slower. This part of the code is actually called very often and tends to be the bottleneck in perfomance.

like image 297
Tomas Pajonk Avatar asked Dec 23 '22 11:12

Tomas Pajonk


1 Answers

Unfortunately you can't.

There's a workaround which Marc Gravell has implemented as part of MiscUtil (with a more general article too). It's neat, but you do lose static type checking.

In a similar vein (in terms of losing type checking) the new dynamic feature of C# 4.0 lets you use operators in an arbitrary way, only resolving them at execution time:

dynamic x = 10.0;
dynamic y = 3.0;
double z = x / y; // z = 3.3333333 (double arithmetic)

dynamic a = 10;
dynamic b = 3;
int c = a / b; // c = 3 (integer arithmetic)

Just this afternoon I used this to implement a dynamic form of Enumerable.Sum. I'm about to benchmark it. Marc Gravell wrote a blog post about this recently, too.

If you're using VB, it's possible that just turning Option Strict off for the section of code where you want late binding will have the same effect, but I'm not as familiar with VB as I am with C#, I'm afraid.

like image 51
Jon Skeet Avatar answered Jan 30 '23 01:01

Jon Skeet