I have a nullable DateTime field "BirthDate" the existing code was handeling this in such a way
info.BirthDate = (DateTime?)reader["Birthdate"];
This causes an "Invalid Cast" error and it breaks. Ok, I understand this is because nulls are returned differently from sql and are of the type "DBNull"
Fix for this turned out to be
if (reader["Birthdate"] != DBNull.Value)
{
info.Birthdate = (DateTime)reader["Birthdate"];
}
Can someone explain why exactly this works?..I'm particularly lost on the .Value part of DBNull. If it IS returning as DBNull how does the code even reach inside this block?