Generics, use mathematical operatos on type parameter

  • Thread starter Thread starter Jock
  • Start date Start date
J

Jock

Hi all,

I would like to use mathematical operators (*, +, etc) on a generic
parameter, see the code below:

public class TestGenerics<T> where ???
{
private T d;
public TestGenerics(int a)
{
d = a * 3;
}
}

Is this possible?
If yes, what constraint should I use on the T type argument?

Thanks
Jock
 
Is this possible?
No. You'll have to work around this problem with an interface or base
class that implements the required functionality.


That what I suspected!
Unfortunately when you deal with native types (int, float, double, etc)
Generics are not so handy!
When will Microsoft provide us a useful Generics implementation similar to
C++ Template?!? :))

Jock
 
When will Microsoft provide us a useful Generics implementation similar
to C++ Template?!? :))

For instance would be very handy having something like that:

public class TestGenerics<T> where T : numeric
{
private T d;
public TestGenerics(int a)
{
d = a * 3;
d = (d + 7) *5;
}
}

"where T : numeric" means that you can apply to T every math operator that
is supported by every numeric *primitive* types.
So the code in the constructor above will be valid!

What do you think?

Jock
 
You could vote for it so that MS is more likely to implement it for
the next release.

Christoph,

Thanks for your suggestion.
I an going to read and vote for the suggestions on the MSDN Product Feedback
Center you point
(I even didn't know that something like that exists!).

I hope we can achieve more power with Generics very soon.

Jock
 
Back
Top