tags:

views:

120

answers:

2

Setting with a ternary

DateTime filterDate = endDate.HasValue ? endDate.Value : DateTime.Now.AddDays(7);

Non ternary

DateTime filterDate;
if (endDate.HasValue)
    filterDate = endDate.Value;
else
    filterDate = DateTime.Now.AddDays(7);

If you debug these two statements the value of filterDate will not be the same. Why is this?

In the first example filterDate ends up with a value of 01/01/0001. In the second example I get the expected result which is filterDate is a datetime 7 days in the future.

EDIT: At this point I've even tried setting endDate = null just to make sure and here is a screen shot of what happens. alt text

Strangest thing I've ever seen.

+5  A: 

I was unable to reproduce this. In any case this is the preferred way of doing this:

DateTime filterDate = endDate ?? DateTime.Now.AddDays(7);
ChaosPandion
+6  A: 

It looks like endDate is being initialized to DateTime.MinValue, can you show the code where you declare endDate?

Also, an even shorter way:

DateTime filterDate = endDate ?? DateTime.Now.AddDays(7);
Nick Craver
I tried it that way first and got the same result as the ternary version. I thought maybe the DateTime object didn't support the null coalescing operator.endDate is a parameter on a mvc controller action. I am not passing anything so it should be null. endDate is null if I quickwatch it.
Jeremy Seekamp
Agreed. Only way I could reproduce the error was to set endDate to min value instead of null.
Bomlin