Unboxing -1 and casting to Nullable <int> using generics gives an InvalidCastException
In this SO post, I found a generic extension method that returns the default value if the value read SqlDataReaderis equal to nullor DBNull.Value, and the value is correctly converted otherwise. I implemented it as follows:
public static T GetValueOrDefault<T>(this SqlDataReader reader, string columnName, T defaultValue = default(T))
{
object val = reader[columnName];
if (val == null || val == DBNull.Value)
{
return defaultValue;
}
return (T)val;
}
The following examples of methods in the above message do not use the correct syntax, but, nevertheless, suggest that this should also work with NULL types such as int?.
However, I read the null column intfrom the database as follows:
MyProperty = reader.GetValueOrDefault<int?>("SomeColumnName")
, val - -1, T - int?, InvalidCastException. , unboxing casting (val object, short), , ? , , .
, , .
int , int. , .
, Convert ; , int ( -1 int, , who-know-where short long - ).
, , , . Convert.ToInt32() .
(.. ) Convert.ChangeType(), , :
public static T GetValueOrDefault<T>(this SqlDataReader reader, string columnName, T defaultValue = default(T))
{
object val = reader[columnName];
if (val == null || val == DBNull.Value)
{
return defaultValue;
}
return (T)Convert.ChangeType(val, typeof(T));
}