Re: Nullable Dates

Tech-Archive recommends: Fix windows errors by optimizing your registry



Hi,

"Jon Skeet [C# MVP]" <skeet@xxxxxxxxx> wrote in message
news:1189693209.830086.194760@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
On Sep 13, 3:12 pm, Wannabe <Wann...@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
I have a start and end date in my application. If a user does not know
their
dates yet, I want them, they will be null in the DB and I want them to be
blank in the application. So, I'm trying to figure out how to use a
nullable
date, and want to return it in my method.

I tried to cast the output parameter, but I get a run-time cast error:
return new TimeLine((DateTime?)command.Parameters["@startDate"].Value,
(DateTime?)command.Parameters["@endDate"].Value);

Then I changed to the code to what you see below, and it worked. But I am
wondering is there a better way to do this when working with nullable
dates?

The simplest way would be:

DateTime? startDate = command.Parameters["@startDate"].Value as
DateTime? ;
DateTime? endDate = command.Parameters["@endDate"].Value as
DateTime? ;

That will work, *but* it will give you null for start/end dates which
are neither DBNull nor DateTime. In other words, it will hide the
error. If you want more rigour, I'd write a helper method to convert
object to DateTime, throwing an exception if the parameter is neither
a DateTime nor DBNull.Value.

If the columns in the DB are of DateTime then it will work as expected.


.



Relevant Pages

  • Re: Nullable Dates
    ... I tried to cast the output parameter, but I get a run-time cast error: ... DateTime? ... I'd write a helper method to convert ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Nullable Dates
    ... are neither DBNull nor DateTime. ... If you want more rigour, I'd write a helper method to convert ...
    (microsoft.public.dotnet.languages.csharp)
  • Trying to set datetime output variable
    ... I have an Execute SQL Task that takes input paramters and then is to ... set one datetime variable as the output parameter. ... paramter there is no "datetime" variable type, ... My database value is set to datetime type, ...
    (microsoft.public.sqlserver.dts)