Reputation: 307
This is the case. I get the date from DatePicker control:
DateTime current = datePicker1.SelectedDate;
And I get an error: Cannot implicitly convert DateTime? to DateTime. So I guess it's up to a nullable type DateTime?.
Is it safe to cast this type to a type I need like this:
if (datePicker1.SelectedDate == null)
current= DateTime.Now;
else
current= (DateTime)datePicker1.SelectedDate; //or datePicker1.SelectedDate.Value
And in general, when is it SAFE to implicitly cast nullable values, and when it isn't?
Upvotes: 2
Views: 3293
Reputation: 1563
Nullable types have a special property for this kind of thinks. It is HasValue, and moreover GetValueOrDefault. So what You really need is
DateTimePicker1.SelectedDate.GetValueOrDefault(DateTime.Now);
// or DateTime.MaxValue or whatever)
.
Upvotes: 4
Reputation: 1501996
In this case you should use the null coalescing operator:
current = datePicker1.SelectedDate ?? DateTime.Now;
That will use SelectedDate
if it's non-null, or DateTime.Now
otherwise. The type of the expression is non-nullable, because the last operand is.
In general, you should use the Value
property (or cast to the non-nullable type) if you're confident that the value is non-null at that point - so that if it is null, it will throw an exception. (If you're confidence is misplaced, an exception is appropriate.) Quite often the null coalescing operator means you don't need to worry about this though.
Upvotes: 4
Reputation: 523464
How about
DateTime current = datePicker1.SelectedDate ?? DateTime.Now;
?
Upvotes: 0
Reputation: 83264
You don't need to cast, the following
if (datePicker1.SelectedDate == null)
current= DateTime.Now;
else
current= datePicker1.SelectedDate.Value;
should do
Upvotes: 0