Reputation: 24729
My DateTime?
with a value minus another DateTime?
with a value is resulting in a null TimeSpan?
.
See the date values have been pinned to the debugger.
I could not replicate this in a console app as it worked with the same dates. The date formats are in dd/mm/yyyy
I understand that I do not need .Value
with the code in places. I have tried without .Value
.
Post-Edit
TimeSpan ts = DateModified.Value - publishRecord.DatePublished.Value;
TimeSpan ts2 = DateModified.Value.Subtract(publishRecord.DatePublished.Value);
TimeSpan? ts3 = DateModified - publishRecord.DatePublished;
All attempts result in that line having the exception as in the screenshot. Nullable object must have a value.
... continuing to dig as per suggestions and show more information as requested...
Post-Edit 2:
Both DateModified and DatePublished are DateTime? standard. The properties are auto get; set;
Post-Edit 3 - Summary
I can't explain this bug. This is a system that is nunit tested. So it is a surprise when something in a well tested area turns this up. This bug appeared during interface development and so was debugging it by attaching to the class library and refreshing the web page. Builds in both solutions were always performed.
I make regular database snapshots and retained the current broken one while going back to a snapshot just prior to the problem. The system worked. Going back to the broken one showed the bug again.
I made a console app and wrote code with the class library reference to perform a similar code track and could not replicate the bug in the "broken" snapshot.
What happened in between working and not working, windows updates, mainly for office software. Missed a coffee break.
I have retained the database snapshot and will see if this problem occurs again in the next few days. If it does not I will at that point delete the question.
Thank you to everyone for your attention and suggestions.
Upvotes: 3
Views: 1087
Reputation: 415810
There is no point in using a Nullable Timespan here in that way. Either both of the DateTime?'s have a value, and you get a regular (non-nullable) TimeSpan, or one or both of the DateTime?'s does not have a value, in which case access the .Value
property will cause an exception. It sounds like you should have code more like this:
TimeSpan? ts = null;
if (DateModified.HasValue && publishRecord.DatePublished.HasValue)
ts = DateModified.Value - publishRecord.DatePublished.Value;
I also noticed this:
I made a console app and wrote code with the class library reference to perform a similar code track and could not replicate the bug in the "broken" snapshot.
Based on that, I'd look for something in another thread that's changing one of those values out from under you. Perhaps try logging the values of DateModified
and publishRecord.DatePublished
before the line executes and again when the exception is thrown. I expect you'll find that one of them has become null
.
Upvotes: 2