DateTime and NULL value

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi everyone,

I've got a class with some strings an datetime fields.
When I set the values of all the members of the class with a datareader,
I've got an error on the DateTime field, which must be NULL.

myAddress.Birthday = DateTime.Parse(drAddress["Birthday"].ToString());
When the Birthday column is NULL in the database, I've got an error.
NULL can't be converted to DateTime.

what is the solution to this problem?

thanks!

Filip
 
Filip said:
Hi everyone,

I've got a class with some strings an datetime fields.
When I set the values of all the members of the class with a
datareader, I've got an error on the DateTime field, which must be
NULL.

myAddress.Birthday = DateTime.Parse(drAddress["Birthday"].ToString());
When the Birthday column is NULL in the database, I've got an error.
NULL can't be converted to DateTime.

what is the solution to this problem?

DateTime is a value type and so can't be null. You have a few choices:

1. If you're using .NET 2.0, you can change your member variable to a
DateTime? (aka Nullable<DateTime>) which can be null.
2. You can choose a distinguished value, such as DateTime.MinValue to
represent null in your code. You'll have to check for that value everywhere
you use the variable and handle it appropriately.
3. You can store a boxed DateTime by changing the type of your variable to
object. You'll have to cast (after checking for null) back to DateTime
whenever you need to use the variable.
4. You can define your own reference class that wraps a DateTime and exposes
as much of the DateTime API as you need.
5. You can use the System.Data.SqlTypes.SqlDateTime type.
.... I'm sure there are lots more.

If you're using 2.0, option 1 is the way to go. If you're using 1.x and
don't mind (or already have) the dependency on System.Data, then I'd say #5
is the way to go.

-cd
 
Back
Top