Specified cast not valid with generic
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