can someone explain this nullable datetime error to me

  • Thread starter Thread starter Peted
  • Start date Start date
P

Peted

Using vs2008 c#

i have this code snipet note: SUBMITTED_DT = DateTime? type

if ((DateTime.Now - billingEvent.SUBMITTED_DT).Days > 180)
{
throw new
BusinessException(Messages.BillingEvent_Save_TooOld);
}


this causes an error on build saying .Days is not supported, and
asking if i am missing an assembly reference.


if i change the code to (ie add SUBMITTED_DT.Value)

if ((DateTime.Now - billingEvent.SUBMITTED_DT.Value).Days > 180)
{
throw new
BusinessException(Messages.BillingEvent_Save_TooOld);
}

then this builds ok, i know its something to do with using DateTime?
but i dont realy understand why.

Can anyone give me a Captain Dummy explanation of why .Value is
required ?


thanks

Peter
 
I see. Ok thanks for that, that makes sense

cheers

Peter

[...]
then this builds ok, i know its something to do with using DateTime?
but i dont realy understand why.

Can anyone give me a Captain Dummy explanation of why .Value is
required ?

Well, I think the "Captain Dummy explanation" is simply "that's just the
way it works". :)

The slightly more complicated explanation is that through the magic of
implicit conversions, subtracting a DateTime? from a DateTime results in a
TimeSpan?, which is actually an instance of Nullable<TimeSpan>, which does
not have a Days property (nor any other property that TimeSpan has).

You have to get back to the non-nullable TimeSpan type in order to have a
type with that property, and one of the ways you can do that is by
short-circuiting the implicit conversions by explicitly getting the
non-nullable DateTime Value property from your DateTime? instance. That
removes the nullable type that was causing the expression type itself to
be nullable, and thus the result is a plain non-nullable TimeSpan, with
the Days property you expect.

There are a variety of ways to write the code so that it works, but they
all involve getting the expression back to the non-nullable TimeSpan
type. For example, in addition to how you solved it, you could have
written:

if (((TimeSpan)(DateTime.Now - billingEvent.SUBMITTED_DT)).Days > 180)

or

if ((DateTime.Now - billingEvent.SUBMITTED_DT).Value.Days > 180)

Pete
 
Back
Top