I seem to recall that it can sometimes by faster to get the value as an object and then check if that's DBNull.
private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex)
{
object value = dataReader.GetValue(fieldIndex);
return value is DBNull ? (Int32?) null : (Int32) value;
}
It's at least worth a try. Note that this is assuming you can unbox straight to an int
... I don't know for sure whether that's correct, but it'll be easy to see.
Now there's another approach which is somewhat less safe - it will return null for any non-integer value, even if the field is actually a string, for example:
private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex)
{
return dataReader.GetValue(fieldIndex) as Int32?;
}
I've previously written about "as" with nullable types not being as fast as I'd expect, but this may be a slightly different case... again, it's worth having a go.
However, I'd be really surprised if this is genuinely a bottleneck... surely getting the data from the database in the first place is going to be far more expensive. Do you have benchmarks for this?