I thought of having a function which performs a numeric conversion ( which can fail or which produces loss of digits ) instead of writing:
double d = 23.4;
int i = (int)d;
My implementation of course doesn't works, because "as" only works with ReferenceTypes ( and as I suppose wouldn't do a numeric conversion.) and using the direct cast isn't possible in Generics ( as far as I know).
public ValueType TrySetNumericValue<ValueType>(double dValue)
{
try
{
ValueType Value;
/* // using as, doesn't works
if(dValue as ValueType != null)
{
Value = dValue as ValueType;
return Value;
}
// this of course works neither,
// I would need a kind of TryCast()...
Value = (ValueType)dValue;
}
catch (Exception e)
{
}
return default(ValueType);
}
If anyone asks himself: why I'm doing such strange stuff, I'm having here a kind of Database holding generic types, where most are Numbers (integers and doubles mixed), but not all.
Thanks for comments,
Florian