tags:

views:

147

answers:

4

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?

A: 

You don't need to cast, the following

if (datePicker1.SelectedDate == null)
   current= DateTime.Now; 
else 
   current= datePicker1.SelectedDate.Value; 

should do

Ngu Soon Hui
according to MSND, datePicker1.SelectedDate.Value is the same as (DateTime)datePicker1.SelectedDate. Both belong to a explicit conversions
trnTash
A: 

How about

DateTime current = datePicker1.SelectedDate ?? DateTime.Now;

?

KennyTM
+4  A: 

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.

Jon Skeet
this worked. thanks for a fast answer!
trnTash
+3  A: 

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).

luckyluke
thanks for an additional info, it's useful as well
trnTash
Thanks a lot luckeyluke. :)
Ismail