Generic methods help

F

Fabrizio Romano

Hello,

I have a problem with a generic method.
I have written a sieve to generate prime numbers. This method takes an input
parameter which is the upperbound of the last prime I need to get. So if I
call
List<int> p = Sieve(10);
I get a List<int> with 2,3,5,7 inside.
Sometimes I need a list of long values so I have another method, called
SieveLong(int upTo) which returns a List<long>. It does the same exact
operations of the int version, but returns a generic list of long values.
Now, I would like to concentrate these 2 methods into one single one, so I
wrote something like:

public List<T> Sieve<T>(int upTo) where T : struct {}

to be able to get a List<int> or a List<long> depending on how I call the
method Sieve<int> or Sieve<long> in my code.
The problem is that when it comes to put into the list the first prime
number (2) I get an error.

the code is something like this:
....
List<T> p=new List<T>();
p.Add((T)2);
....

It tells me that it can't convert int to T. I tried adding different
constraints, like IComparable, IConvertible, and so on, but I can't get this
to work.

Basically I need that depending on how I call the Sieve method, it returns
me a certain type list, like this:

List<int> p = Sieve<int>(upTo);
or
List<long> p=Sieve<long>(upTo);

and I would like this to be possible with Int16, Int32, Int64 types.
Any help?

Thank you very much,
Fabrizio
 
M

Marc Gravell

If you are using .NET 3.5 then yes!
This very morning Jon released some of my code in the MiscUtil library
(link below) that includes generic operator support, and an equally
handy Convert mechanism.

Operators: http://www.pobox.com/~skeet/csharp/genericoperators.html
Download: http://www.pobox.com/~skeet/csharp/miscutil/

For instance, you can use:

p.Add(Operator.Convert<int,T>(2));

You might also (instead) be able to cast to object in the middle, but
the above avoids a box. Additionally, I suspect that you might find
the other Operator.{blah} methods (divide, add, multiply, etc) handy;
note that it doesn't include a Modulo function at the moment (which
would be handy here), but I could add one if needed?

However!!!! Since there are only 3 types here, you might also consider
simply having SieveInt32, SieveInt64; but of course, if this code is
at the bottom of a pile of generics, then the Operator.{blah} approach
may be more useful (since you can use Sieve<T> for whichever T you
happen to have...)

Marc
 

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