简体   繁体   中英

Nullable datetime value from DatePicker

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?

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.

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

You don't need to cast, the following

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

should do

How about

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

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM