In a legacy application, we have a SqlDataReader
. The following field creates a InvalidCastException
with a bit
field.
public static T GetValueOrNull<T>(this IDataReader reader, string column)
{
int ordinal;
if(!string.IsNullOrEmpty(column) && !reader.IsDBNull(reader.GetOrdinal(column)))
if(int.TryParse(reader.GetOrdinal(column).ToString(), out ordinal))
return (T)reader.GetValue(ordinal);
return default(T);
}
What is odd, is that (T)reader.GetValue(ordinal)
does assign a valid type. It assigns a false
, but the error still occurs. I'm not entirely sure why.
If I perform GetType();
it does indeed show Boolean
type. I've also checked to ensure that it is threadsafe.