Reputation: 1161
In a nutshell I'm trying to get this code working:
class it<X>
{
X[] data;
int pos;
public Y get<Y>()
{
return (Y) data[pos];
}
}
Basically, I have lots of arrays of different primitives that needs to be processed another place as different primitives. The former code won't compile because the compiler doesn't know what X and Y is. The following, does, however:
public Y get<Y>()
{
return (Y) (object) data[pos];
}
However, then I get runtime exceptions like:
InvalidCastException: Cannot cast from source type to destination type.
it[System.Double].get[Single]()
Which seems silly because C# obviously has a cast between floats and doubles (and other primitives). I'm guessing it has something to do with boxing and such, but I'm pretty new to C# so I don't really know - I guess I'm used to C++ templates. Note that a conversion between X and Y always exists - can I tell the compiler this, some way?
Upvotes: 0
Views: 65
Reputation: 6030
You could use Convert
's ChangeType
-method:
public Y get<Y>()
{
return (Y)Convert.ChangeType(data[pos], typeof(Y));
}
It might also be a good idea to add some generic constraints to your class and method to ensure only primitives can be passed:
class it<X> where X : struct
public Y get<Y>() where Y : struct
Upvotes: 1