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