Generic Generics Problem 2

T

Tom Jastrzebski

Hello everybody,

Here is another problem with generics I come across.

Let's say I want to implement a structure performing some operations on some
numeric type.
I can not than just return this expected type since the compiler is not sure
what this type would be, and it does not know that the type I am trying to
returned is the correct type, or either that the conversion is possible. Ok,
I understand - it is just the limitation of generics.

The solution I found was converting my type value to an object and then
downcasting from an object. That is I have to box and unbox my value type to
make the compiler happy paying significant performance price.

My question is: am I missing something? What sense does it make all
together, I mean placing restriction on conversion from my known type, that
is, assuming I may not know what I am doing, but allowing conversion from an
object. I just do not see any sense here.

Tomasz


Disclaimer: of course the attached example is just an example. This
particular functionality can be achieved in a different way.

sample usage:

int maxVal = MyGenericStruct<Int32>.GetMaxValue();

struct MyGenericStruct<T> where T : struct, IConvertible
{
public static T GetMaxValue()
{
TypeCode tc = default(T).GetTypeCode();

switch (tc) {
case TypeCode.Int32:
return (T)Int32.MaxValue; // causes compile error
// but this works:
object o = Int32.MaxValue;
return (T)o;
// [support for other types]
default:
throw new InvalidEnumArgumentException();
}
}
}
 
C

Christoph Nahr

I don't know of a way to solve your specific problem. However, all
discussions I've seen regarding generics imply that are basically
unusable for numerics. Sorry... you'll have to use traditional
overloading and/or multiple classes for each type.
 
T

Tom Jastrzebski

Chris,

I do not think this problem is by any means limited to only numeric types.

Tomasz
 
C

Christoph Nahr

Well, numerics is the only case I can think of where you have a bunch
of value types and frequently want to convert from one to another.
Structs aren't (or shouldn't be) used very often otherwise.
 

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