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
You could try by using the IConvertible Interface, so it will at least work for types that implement it. Beware, this can still throw exceptions for types which do not make use of it, but for your conversions it's doing just fine:
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)Convert.ChangeType(currentValue,typeof(T));
}
Concerning your cast to int from float: you are trying to convert a boxed type - it was boxed when you called your method which effectively converted it to an object. Boxed types can only be cast back to themselves. Since a cast to int is not the same type, it will not work. To reproduce without generics try this, it will also throw an InvalidCastException
:
float currValue = 20.1f;
object yourValue = currValue;
int i = (int) yourValue; //throws as well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With