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