I seem to recall that sometimes it can be faster to get the value as an object, and then check if this DBNull is not.
private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex) { object value = dataReader.GetValue(fieldIndex); return value is DBNull ? (Int32?) null : (Int32) value; }
It is at least worth a try. Please note that this assumes that you can unzip directly to int ... I donβt know exactly if this is correct, but it will be easy to see.
Now there is another approach that is somewhat less secure - it will return null for any non-integer value, even if this field is actually a string, for example:
private Int32? GetNullableInt32(SqlDataReader dataReader, int fieldIndex) { return dataReader.GetValue(fieldIndex) as Int32?; }
Earlier, I wrote about the βhowβ with null-value types that were not as fast as I expected, but that might be a little different thing ... again, it's worth the time.
However, I would be very surprised if this is really a bottleneck ... of course, getting data from the database in the first place will be much more expensive. Do you have guidelines for this?
Jon skeet
source share