Null values in C#

Reading null values from datatabase in C# code

If you tried reading a null value from the database such as a null date, you might have across this exception

Specified cast is not valid

Casting Nullable Values

The following code works unless a null datetime is returned. Note that DateTime is followed by ? which means this date can accept a null value therefore nullabe.


/* assume nullable datetime in the database */
DateTime? exportDate = null;
exportDate = (DateTime)cmd.ExecuteScalar();

This is a little bit strange that you cannot use DateTime? operator to cast the return value as a nullable datetime. Although you can use it and it will not give you error, it does not give you the required result. That is it does not cast null values. To cast null values you must use As Operator.

Use As Operator with Nullable values

To case a nullable value, you must use As operator in C#. Also you must return the datetime as nullable field. The following is the correct version of the above code, which failed to return null values.


/* assum nullable datetime in the database */
DateTime? exportDate = null;
exportDate = cmd.ExecuteScalar() as DateTime?;