Generics, use mathematical operatos on type parameter

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
 
J

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
 
J

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
 
J

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top