I have this function that checked the current value. When the current value (1st parameter) is null or empty, then it uses the default value you pass (2nd paramter)
public static T ZeroNull<T>(object currentValue, T defaultValue)
{
if (currentValue.Equals(DBNull.Value))
return (T)defaultValue;
else if (currentValue.Equals(string.Empty))
return (T)defaultValue;
else
return (T)currentValue;
}
The code above is working properly, partially... But when I use the code like this, it throws an "Specified cast is not valid..."
float currValue = 20.1f;
int i = ZeroNull<int>(currValue, 0); // Specified cast is not valid
int i = ZeroNull<int>("10", 0); // Specified cast is not valid
Anybody can improve the above code snip? And why the compiler throw this error?
Regards, Jessie
currValue
is a boxed float (20.1f) and your trying to unbox to a int which isn't valid. The same goes for "10" – Sitcode
float currValue = 10.2f;code
int newCurrValue = (int)currValue; I just assuming they have the same logic? – Deepfry(T)currentValue
– Korikorie??
? Do you have a DataTable that uses strings instead of numeric types? – Technician_defaultMinValue = PFDMSDataCollection.ZeroNull<double>(datarow["dblDefaultMinValue"], 0.0);
_defaultMaxValue = PFDMSDataCollection.ZeroNull<double>(datarow["dblDefaultMaxValue"], 0.0);
– Deepfry