Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert 'System.TimeSpan?' to 'System.TimeSpan'

The below code works fine :

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
int d3 = (int)(d1 - d2).TotalDays;

But what if I define DateTime as DateTime? :

DateTime? d1 = DateTime.Now;
DateTime? d2 = DateTime.Now.AddDays(-1);
int d3 = (int)(d1 - d2).TotalDays;

underlined red with error

Cannot implicitly convert 'System.TimeSpan?' to 'System.TimeSpan'

Is it possible to get the difference of number of days between two datetimes that are defined as nullable?

like image 554
Bilal Ahmed Avatar asked Jul 23 '16 12:07

Bilal Ahmed


2 Answers

Well yes, but you need to use the Value property to "un-null" it:

int d3 = (int)(d1 - d2).Value.TotalDays;

However, you should consider the possibility that either d1 or d2 is null - which won't happen in your case, but could in other cases. You may want:

int? d3 = (int?) (d1 - d2)?.TotalDays;

That will give a result of null if either d1 or d2 is null. This is assuming you're using C# 6, of course - otherwise the ?. operator isn't available.

(You could use GetValueOrDefault() in the first case as suggested by user3185569, but that would silently use an empty TimeSpan if either value is null, which feels unlikely to be what you want.)

like image 139
Jon Skeet Avatar answered Oct 26 '22 19:10

Jon Skeet


Yes, using GetValueOrDefault():

DateTime? d1 = DateTime.Now;
DateTime? d2 = DateTime.Now.AddDays(-1);
int d3 = (int)(d1 - d2).GetValueOrDefault().TotalDays;

d1 - d2 return Nullable TimeSpan which doesn't directly contains a property called TotalDays. But using GetValueOrDefault() you can return a TimeSpan object and get 0 Total Days if the value was NULL

If you do really expect Null Values, it is better to differentiate between 0 days (What the above approach returns) and and invalid operation (date - null), (null - date) and (null - null). Then you might need to use another approach:

int? d3 = (int) (d1 - d2)?.TotalDays;

Or if you're using a version prior to C# 6 :

int? d3 = d1.HasValue && d2.HasValue ? (int)(d1 - d2).Value.TotalDays : new int?();
like image 31
Zein Makki Avatar answered Oct 26 '22 20:10

Zein Makki