TimeSpan

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have the following:

boxStat = new BoxStat {
BoxCount = database.Boxes.Count(),
SinceLastCreate = (DateTime.Now - database.Boxes.Max(b =>
b.CreatedAt)).Days ?? 0
};

I am getting an error:
'System.Nullable<System.TimeSpan>' does not contain a definition for
'Days' and no extension method 'Days' accepting a first argument of
type 'System.Nullable<System.TimeSpan>' could be found (are you
missing a using directive or an assembly reference?)

I added ?? 0 to try to solve the problem but I keep having the same
error.

What am I doing wrong?

Thank You,
Miguel
 
For whatever reason , DateTime math has always seemed to require an explicit
cast to TimeSpan :

SinceLastCreate = ( (TimeSpan) (DateTime.Now - database.Boxes.Max(b
=> b.CreatedAt)) ).Days
 
shapper has brought this to us :
Hello,

I have the following:

boxStat = new BoxStat {
BoxCount = database.Boxes.Count(),
SinceLastCreate = (DateTime.Now - database.Boxes.Max(b =>
b.CreatedAt)).Days ?? 0
};

I am getting an error:
'System.Nullable<System.TimeSpan>' does not contain a definition for
'Days' and no extension method 'Days' accepting a first argument of
type 'System.Nullable<System.TimeSpan>' could be found (are you
missing a using directive or an assembly reference?)

I added ?? 0 to try to solve the problem but I keep having the same
error.

What am I doing wrong?

Thank You,
Miguel

What does "database.Boxes.Max()" return? I'm guessing a nullable
DateTime (either "DateTime?" or "Nullable<DateTime>", they are the
same).

That means that that difference will not return a TimeSpan, but a
nullable TimeSpan.
That "TimeSpan?" does not have a "Days" property, but it has a Value
property that returns a TimeSpan. That *does* have a Days property.
(DateTime.Now - database.Boxes.Max(b => b.CreatedAt)).Value.Days

Note: this fails if that Max returns a null!


You could have used that ?? operator, but then at the point where a
nullable type was involved:
((DateTime.Now - database.Boxes.Max(b => b.CreatedAt)) ??
TimeSpan.Zero).Days
This way you get 0 days when Max returned null.

Or (as gerry suggested) cast to TimeSpan before reading the Days
property. But this also fails when Max returns null.

Hans Kesting
 
Back
Top