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();
}
}
}