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?;

Advertisements
This entry was posted in Troubeleshoot and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s